Rotating an image with orientation specified in EXIF using Python without PIL including the thumbnail
This solution works for me:PIL thumbnail is rotating my image?
Don't need to check if it's iPhone or iPad:if photo has orientation tag – rotate it.
from PIL import Image, ExifTagstry: image=Image.open(filepath) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break exif = image._getexif() if exif[orientation] == 3: image=image.rotate(180, expand=True) elif exif[orientation] == 6: image=image.rotate(270, expand=True) elif exif[orientation] == 8: image=image.rotate(90, expand=True) image.save(filepath) image.close()except (AttributeError, KeyError, IndexError): # cases: image don't have getexif pass
Before:
After:
If you're using Pillow >= 6.0.0, you can use the built-in ImageOps.exif_transpose
function do correctly rotate an image according to its exif tag:
from PIL import ImageOpsimage = ImageOps.exif_transpose(image)
Pretty much the same answer than @scabbiaza, but using transpose instead of rotate (for performance purposes).
from PIL import Image, ExifTagstry: image=Image.open(filepath) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break exif=dict(image._getexif().items()) if exif[orientation] == 3: image=image.transpose(Image.ROTATE_180) elif exif[orientation] == 6: image=image.transpose(Image.ROTATE_270) elif exif[orientation] == 8: image=image.transpose(Image.ROTATE_90) image.save(filepath) image.close()except (AttributeError, KeyError, IndexError): # cases: image don't have getexif pass