I’m attempting to take large (huge) images (from a digital camera), and convert them into something that I can display on the web. This seems straightforward, and probably should be. However, when I attempt to use PIL to create thumbnail versions, if my source image is taller than it is wide, the resulting image is rotated 90 degrees, such that the top of the source image is on the left of the resulting image. If the source image is wider than it is tall, the resulting image is the correct (original) orientation. Could it have to do with the 2-tuple I send in as the size? I’m using thumbnail, because it appears it was meant to preserve the aspect ratio. Or am I just being completely blind, and doing something dumb? The size tuple is 1000,1000 because I want the longest side to be shrunk to 1000 pixels, while keeping AR preserved.
Code seems simple
img = Image.open(filename)
img.thumbnail((1000,1000), Image.ANTIALIAS)
img.save(output_fname, "JPEG")
Thanks in advance for any help.
Please note that there are better answers below.
When a picture is taller than it is wide, it means the camera was rotated. Some cameras can detect this and write that info in the picture’s EXIF metadata. Some viewers take note of this metadata and display the image appropriately.
PIL can read the picture’s metadata, but it does not write/copy metadata when you save an Image. Consequently, your smart image viewer will not rotate the image as it did before.
Following up on @Ignacio Vazquez-Abrams’s comment, you can read the metadata using PIL this way, and rotate if necessary:
But be aware that the above code may not work for all cameras.
The easiest solution maybe to use some other program to make thumbnails.
phatch is a batch photo editor written in Python which can handle/preserve EXIF metadata. You could either use this program to make your thumbnails, or look at its source code to see how to do this in Python. I believe it uses the pyexiv2 to handle the EXIF metadata. pyexiv2 may be able to handle EXIF better than the PIL’s ExifTags module.
imagemagick is another possibility for making batch thumbnails.