0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rotate photos based on exif orientation

Posted at
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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?