rotate photos based on exif orientation

More than 3 years have passed since last update.

from PIL import Image

import piexif

def rotate_img(img, rotate_param):
e = piexif.load(img.info["exif"])
e['0th'][274] = 1 # no rotate
if rotate_param in [Image.ROTATE_90, Image.ROTATE_270]:
e['Exif'][40962], e['Exif'][40963] \
= e['Exif'][40963], e['Exif'][40962] # swap width, height

img = img.transpose(rotate_param)
output = BytesIO()
img.save(output, 'JPEG', quality=90, exif=piexif.dump(e))
length = output.tell()
output.seek(0)
return img, output, length

img = Image.open('file')
e = piexif.load(img.info["exif"])
if self.exif and 'Orientation' in self.exif:
if self.exif['Orientation'] == 3:
img, output, length = rotate_img(self, img, Image.ROTATE_180)
elif self.exif['Orientation'] == 6:
img, output, length = rotate_img(self, img, Image.ROTATE_270)
elif self.exif['Orientation'] == 8:
img, output, length = rotate_img(self, img, Image.ROTATE_90)