Realization method of automatic rotation of image read by Python PIL

  • 2021-07-09 08:52:41
  • OfStack

For the photos taken by mobile phones, cameras and other devices, due to the different hand-held directions, the photos taken may be rotated by 0, 90, 180 and 270. Even if they are turned positive by software on the computer, their exif information will still keep the location information.

When reading these images with PIL, the original data is read, that is to say, even if the normal photos are displayed on the computer screen, they may be rotated images after being read in with PIL, and the size of the pictures may not be the same as those on the screen.

In this case, you can use PIL to read orientation information in exif, and then turn the picture into a positive one according to this information, and then carry out subsequent operations, as follows.


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

Incidentally, "expand = True" in rotate here means that the picture size is also transformed accordingly. If this sentence is not added, size will remain unchanged.

For details, see: https://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image


Related articles: