Search code examples
pythonimageexifpython-imaging-library

Manually set Exif property and maintain image's original width and height in Python


When I do Image.open in python it sometimes flips the width and height of the image. After some research (see this post's explaination), it seems that if the image has Exif Orientation metadata associated with it, then that will cause applications that respect that property to rotate it.

So first I test my image's Exif property by doing

identify -verbose image.JPG | grep Orientation

It returns 6, which means the image has the property and therefore will be flipped. If the response is 1 then the image does not have Exif Orientation metadata and therefore is not flipped. Since I do not want to flip the image, I tried setting the Exif property manually by taking a suggestion from this post.

So I tried setting orientation.exif.primary.Orientation[0] = 1 manually in my code. Like this:

from PIL import Image
import pexif


orientation = pexif.JpegFile.fromFile('image.JPG')

print("BEFORE:")
print(orientation.exif.primary.Orientation[0])

orientation.exif.primary.Orientation[0] = 1

print("AFTER:")
print(orientation.exif.primary.Orientation[0])


img = Image.open('image.JPG')
print(img.size)

This corrects prints 1 after AFTER however, it does not actually set it to 1 in real life because when I run identify -verbose image.JPG | grep Orientation again, it is still showing 6. So how do I actually get around this issue and not have the image's width and height flipped?


Solution

  • I do not take credit for this. This post from Superuser solved my issue.

    Fix:

    import os
    os.system("exiftool -Orientation=1 -n image.JPG")
    

    This sets the orientation of the actual image to 1. The code I had in the original question changes the orientation of the image object I created, not the actual image itself.