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的強大。