Skip to content

Instantly share code, notes, and snippets.

@2minchul
Last active December 28, 2020 04:45
Show Gist options
  • Save 2minchul/e11b84f7d54cc4f66852ba2c80bdc8e1 to your computer and use it in GitHub Desktop.
Save 2minchul/e11b84f7d54cc4f66852ba2c80bdc8e1 to your computer and use it in GitHub Desktop.
transpose exif orientation with PIL
import io
import os
from PIL import Image
from PIL.JpegImagePlugin import JpegImageFile
class Orientation:
key = 0x0112 # see: PIL.ExifTags.TAGS
flip_horizontal = 2
rotate_180_left = 3
flip_vertical = 4
flip_vertical_rotate_90_right = 5
rotate_90_right = 6
flip_horizontal_rotate_90_right = 7
rotate_90_left = 8
def transpose_orientation(img: JpegImageFile):
exif = img.getexif()
try:
orientation = exif[Orientation.key]
except KeyError:
return img
if orientation in (Orientation.flip_horizontal, Orientation.flip_horizontal_rotate_90_right):
img = img.transpose(Image.FLIP_LEFT_RIGHT)
if orientation in (Orientation.flip_vertical, Orientation.flip_vertical_rotate_90_right):
img = img.transpose(Image.FLIP_TOP_BOTTOM)
if orientation == Orientation.rotate_180_left:
img = img.transpose(Image.ROTATE_180)
if orientation in (Orientation.rotate_90_right,
Orientation.flip_vertical_rotate_90_right,
Orientation.flip_horizontal_rotate_90_right):
img = img.transpose(Image.ROTATE_270)
if orientation == Orientation.rotate_90_left:
img = img.transpose(Image.ROTATE_90)
return img
def main():
target_dir = 'exif-orientation-examples' # http://github.com/recurser/exif-orientation-examples.git
output_dir = 'output'
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(target_dir):
if not filename.endswith('.jpg'):
continue
filepath = os.path.join(target_dir, filename)
with open(filepath, 'rb') as f:
img_bytes = f.read()
img = Image.open(io.BytesIO(img_bytes))
new_img = transpose_orientation(img)
new_img.save(os.path.join('output', filename))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment