在缩小图像时保留时间戳
我的数码相机拍的照片分辨率很高,我有一个PIL脚本可以把它们缩小到800x600(或者600x800)。不过,我希望缩小后的文件能保留原来的时间戳。我在文档中看到可以在PIL的图像保存方法中使用文件对象,而不是直接用文件名,但我不知道这样做是否有用。
我的代码基本上是这样的:
name, ext = os.path.splitext(filename)
# open an image file (.bmp,.jpg,.png,.gif) you have in the working folder
image = Image.open(filename)
width = 800
height = 600
w, h = image.size
if h > w:
width = 600
height = 800
name = name + ".jpg"
shunken = image.resize((width, height), Image.ANTIALIAS)
shunken.save(name)
谢谢你能提供的任何帮助!
1 个回答
5
可以使用 shutil.copystat
这个工具。
看起来PIL(Python Imaging Library)并不能保存EXIF元数据。如果你想用Python复制EXIF数据,可以试试 pyexiv2。比如,Phatch这个用Python写的批量照片调整大小的程序就是这样处理EXIF数据的。
我不确定你是不是在用Ubuntu系统,如果是的话,安装起来很简单,因为 pyexiv2
是通过 python-pyexiv2
这个包提供的。
补充:如果你不介意丢失EXIF元数据,只是想把EXIF中的日期时间戳作为调整后图片的修改日期,那么你可以不使用 pyexiv2
包,这样就省去了一个额外的依赖。方法如下:
import os
import time
import Image
import ExifTags # This is provided by PIL
img=Image.open(filename,'r')
PIL可以读取EXIF数据,但目前还不能写入EXIF数据。我们可以通过 _getexif()
方法来访问这些数据:
d = dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items())
print(d['DateTimeOriginal'])
解析时间戳可能要看相机使用的格式。这种方法适用于我的相机;你的情况可能会有所不同。dateutils
这个包可以让你解析多种时间戳,而不需要你提前指定格式,但这又是另一个话题。
timestamp=time.strptime(d['DateTimeOriginal'],"%Y:%m:%d %H:%M:%S")
这里有一种替代方法来交换宽度和高度:
w, h = img.size
width,height = 800,600
if h > w: width,height = height,width
调整图片大小,并使用 os.utime
来修正访问时间和修改时间:
filename = filename + "-800x600.jpg"
shunken = img.resize((width, height), Image.ANTIALIAS)
shunken.save(filename)
st = os.stat(filename)
os.utime(filename,(st.st_atime,time.mktime(timestamp)))