开发者

Preserve time stamp when shrinking an image

My digital camera takes pictures with a very high resolution, and I开发者_运维技巧 have a PIL script to shrink them to 800x600 (or 600x800). However, it would be nice for the resultant file to retain the original timestamp. I noticed in the docs that I can use a File object instead of a name in PIL's image save method, but I don't know if that will help or not.

My code is basically 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)

Thank you for any help you can give!


Use shutil.copystat

It appears that PIL does not save EXIF metadata. To copy the EXIF data using Python you could use pyexiv2. This is how Phatch, a batch photo resizer program written in Python, deals with EXIF data, for example.

I'm not sure if you're using Ubuntu, but if so, installation is easy since pyexiv2 is provided by python-pyexiv2 package.

Edit: If you don't mind losing the EXIF metadata, and would simply like to use the EXIF datetime stamp as the resized image's modification date, then you can do it without the pyexiv2 package, thus saving you an extra dependency. Here's how:

import os
import time
import Image
import ExifTags   # This is provided by PIL
img=Image.open(filename,'r')

PIL can read EXIF data, but cannot yet write EXIF data. We can access the data using the _getexif() method:

d = dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items())
print(d['DateTimeOriginal'])

Parsing the timestamp may depend on what format the camera uses. This works for my camera; YMMV. The dateutils package allows you to parse a wide variety of timestamps without you having to pre-specify the format, but that's another story.

timestamp=time.strptime(d['DateTimeOriginal'],"%Y:%m:%d %H:%M:%S")

Here's an alternative way to swap the width and height:

w, h = img.size
width,height = 800,600
if h > w: width,height = height,width

Resizing the image, and using os.utime to fix the atime and mtime:

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)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜