views:

2387

answers:

4

I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:

img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
    width,height = height,width

resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')

Any ideas? Or other libraries that I could be using?

+7  A: 
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')

http://www.emilas.com/jpeg/

J.F. Sebastian
However, this will save wrong information, especially regarding the X and Y resolutions.
Roberto Liffredo
Nothing prevents you from updating corresponding field in the EXIF info before saving it.
J.F. Sebastian
And when the exif data are to long, you get this error : http://stackoverflow.com/questions/1606514/how-to-use-pil-to-resize-and-apply-exif-information-to-the-file
Natim
As of Oct 2010 http://www.emilas.com/jpeg/ is a broken link
Jake
@Jake: you can try http://tilloy.net/dev/pyexiv2/ as suggested by @iny http://stackoverflow.com/questions/400788/resize-image-in-python-without-losing-exif-data/403293#403293 . Links for old content (jpeg module): http://web.archive.org/web/20080425064422/http://www.emilas.com/jpeg/ http://code.google.com/p/pipp/downloads/detail?name=jpeg-0.1.5.win32.zip
J.F. Sebastian
Thanks @J.F. Sepastian, pyexiv2 looks like the best took for the job but it has a lot of dependencies for a seemingly simple task.
Jake
A: 

PIL handles EXIF data, doesn't it? Look in PIL.ExifTags.

PEZ
resize() deletes EXIF information, and there's no way to put it back in PIL, AFAICT. You can get the data with img._getexif(), but after the resize the method no longer exists
Vinko Vrsalovic
A: 

Why not using ImageMagick?
It is quite a standard tool (for instance, it is the standard tool used by Gallery 2); I have never used it, however it has a python interface as well (or, you can also simply spawn the command) and most of all, should maintain EXIF information between all transformation.

Roberto Liffredo
It just happens that PIL is the standard tool in python and so ImageMagick python bindings are not that well available.
iny
In that case, I would spawn a separate process. ImageMagick (as an executable) is available on almost every configuration.
Roberto Liffredo
+1  A: 

You can use pyexiv2 to modify the file after saving it.

iny