Skip to content

Instantly share code, notes, and snippets.

@willjobs
Created January 31, 2021 02:26
Show Gist options
  • Save willjobs/746569633a6d3728599ad01388ba4ce2 to your computer and use it in GitHub Desktop.
Save willjobs/746569633a6d3728599ad01388ba4ce2 to your computer and use it in GitHub Desktop.
Autorotate images based on EXIF data (iOS)
##############################
# Script to autorotate all images in a directory based on EXIF data.
# Background: iOS devices have a bad habit of saving images with a rotation stored in the
# EXIF data, which is ignored by other applications, resulting in these images
# looking rotated 90 degrees or 270 degrees in many apps. This fixes that.
## CAREFUL - this removes the EXIF information like date taken
##############################
from PIL import Image, ExifTags
import glob
import os.path
files = glob.glob('*.jpg')
count = 0
for file in files:
try:
image=Image.open(file)
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation]=='Orientation':
break
exif=dict(image._getexif().items())
rot = 0
if exif[orientation] == 3:
rot = 180
elif exif[orientation] == 6:
rot = 270
elif exif[orientation] == 8:
rot = 90
if rot != 0:
image=image.rotate(rot, expand=True)
print('Rotated "' + os.path.basename(file) + '" by ' + str(rot) + ' degrees')
count = count + 1
image.save(file)
image.close()
except (AttributeError, KeyError, IndexError):
# cases: image didn't have getexif
pass
print('Finished! Rotated ' + str(count) + ' images.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment