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