Python操作图片的元数据信息

在水木的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 pyexiv22. 获取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 pyexiv2import ospath = '/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'].valueprint metadata['Exif.Image.Software'].valueprint metadata['Exif.Image.ExifTag'].valuekey = '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].valuemetadata[key].value ='A new comment.'metadata.write()print metadata[key].valueprint '--------------------------------------------------------------'

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

另外,还可以尝试一下PIL(Python Imaging Library),不过貌似PIL的功能没有pyexiv2的强大。PIL见:http://www.pythonware.com/products/pil/

Original article: Python操作图片的元数据信息

©2013 笑遍世界. All Rights Reserved.

Python操作图片的元数据信息

相关文章:

你感兴趣的文章:

标签云: