SoFunction
Updated on 2024-11-19

Python PIL implementation for automatic rotation of images read by PIL

For photos taken with cell phones, cameras, and other devices, the photos may be taken rotated 0°, 90°, 180°, and 270° due to the different handheld orientation. Even if they are turned correctly using software on a computer, they will still retain orientation information in their exif information.

When reading these images with PIL, the raw data is read, which means that even if a normal photo is displayed on the computer screen, when it is read in with PIL, it may be a rotated image, and the size of the picture may not be the same as that on the screen.

For this case, you can use PIL to read the orientation information in the exif, and then according to this information, the image will be converted to positive, and then carry out subsequent operations as follows.

from PIL import Image, ExifTags
img = (file)
try:
  for orientation in () : 
    if [orientation]=='Orientation' : break 
  exif=dict(img._getexif().items())
  if  exif[orientation] == 3 : 
    img=(180, expand = True)
  elif exif[orientation] == 6 : 
    img=(270, expand = True)
  elif exif[orientation] == 8 : 
    img=(90, expand = True)
except:
  pass

By the way, the "expand = True" in rotate here is to transform the image size accordingly. If you don't add this line, the size will remain unchanged.

For details, see:/questions/4228530/pil-thumbnail-is-rotating-my-image

This is the whole content of this article.