Skip to content

Instantly share code, notes, and snippets.

@JackStouffer
Created December 1, 2014 03:08
Show Gist options
  • Save JackStouffer/2902dd82fcc8df30e10c to your computer and use it in GitHub Desktop.
Save JackStouffer/2902dd82fcc8df30e10c to your computer and use it in GitHub Desktop.
Fix the EXIF image rotation browser bug by rotating the image manually
from PIL import Image
def autorotate(path):
""" This function autorotates a picture based upon its EXIF data
because smartphones use a little used EXIF option to set the
rotation of an image rather than save the data in that orientation
"""
image = Image.open(path)
try:
exif = image._getexif()
except:
return False
if not exif:
return False
orientation_key = 274 # cf ExifTags
if orientation_key in exif:
orientation = exif[orientation_key]
rotate_values = {
3: 180,
6: 270,
8: 90
}
if orientation in rotate_values:
# Rotate and save the picture
image = image.rotate(rotate_values[orientation])
image.save(path, quality=100)
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment