一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python使用pyexiv2库操作图片的实例教程

时间:2015-03-12 编辑:简简单单 来源:一聚教程网

pyexiv2是exiv2库的Python绑定,而exiv2是用于操作EXIF、IPTC和XMP图片元数据的C++程序库。

关于pyexiv2,请查看其官方网站:http://tilloy.net/dev/pyexiv2/

目前pyexiv2貌似还没支持Python3,本文是用的 Python2.7 做的实验。

在Ubuntu中安装pyexiv2的命令为: apt-get install python-pyexiv2

在Python中使用pyexiv2主要需要注意一下几点即可:
1. import pyexiv2
2. 获取metadata对象:pyexiv2.ImageMetadata(image-file)
3. metadata.read() 用于读取图片的元数据
4. metadata.write() 用于将图片的元数据写回去
5. metadata[key] = value 可以创建或者修改原数据中的某个键值对

使用pyexiv2的示例代码如下:

#!/usr/bin/python2.7
# just a sample for using python-pyexiv2 Library
# pyexiv2 is a Python binding to exiv2,
#        the C++ library for manipulation of EXIF, IPTC and XMP image metadata.
 
import pyexiv2
import os
 
path = '/home/master/Pictures/wall-paper'
for file in os.listdir(path):
    print 'file:' + os.path.join(path,file)
    print '--------------------------------------------------------------'
    metadata = pyexiv2.ImageMetadata(os.path.join(path,file))
    metadata.read()
    print metadata['Exif.Image.DateTime'].value.strftime('%A %d %B %Y, %H:%M:%S')
    print metadata['Exif.Image.ImageDescription'].value
    print metadata['Exif.Image.Software'].value
    print metadata['Exif.Image.ExifTag'].value
    key = 'Exif.Photo.UserComment'
    value = 'A comment.'
    metadata[key] = pyexiv2.ExifTag(key, value)
    # metadata[key] = value    # this a shotcut method as the previous line.
    metadata.write()
    print metadata[key].value
    metadata[key].value ='A new comment.'
    metadata.write()
    print metadata[key].value
    print '--------------------------------------------------------------'

在我的一个系统上运行结果如下:
master@jay-linux:~/workspace/python$ ./pyexiv2-sample.py
file:/home/master/Pictures/wall-paper/855402454225855163.jpg
————————————————————–
Sunday 17 April 2011, 23:59:29
OLYMPUS DIGITAL CAMERA
Adobe Photoshop CS4 Windows
992
A comment.
A new comment
————————————————————–
file:/home/master/Pictures/wall-paper/723672165124933357.jpg
————————————————————–
Sunday 17 April 2011, 23:55:11
OLYMPUS DIGITAL CAMERA
Adobe Photoshop CS4 Windows
992
A comment.
A new comment
————————————————————–

另外,还可以尝试一下PIL(Python Imaging Library),不过貌似PIL的功能没有pyexiv2的强大。

热门栏目