在水木的Python版上看到如何使用Python获取或修改图片的元数据信息的帖子。根据其中一个人的推荐,我顺便使用了一下“pyexiv2”库来试了一下,感觉还不错。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的示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#!/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的强大。
PIL见:http://www.pythonware.com/products/pil/
One Comment