Skip to content

Instantly share code, notes, and snippets.

@pixies
Forked from sxslex/assert_rotation_image.py
Created November 9, 2017 15:32
Show Gist options
  • Save pixies/be0a33ffd7510eec8af024105982d21a to your computer and use it in GitHub Desktop.
Save pixies/be0a33ffd7510eec8af024105982d21a to your computer and use it in GitHub Desktop.
assert_rotation_image
# -*- coding: latin1 -*-
"""
Codigo para colocar uma imagem na orientacao correta.
"""
from PIL import Image
from PIL.ExifTags import TAGS
def get_exif(img):
info_exif = {}
try:
# http://www.exiv2.org/tags.html
if not hasattr(img, '_getexif'):
return {}
info = getattr(img, '_getexif')()
if info:
for tag, value in info.items():
param = TAGS.get(tag, tag).lower()
if isinstance(value, str) and '\x00' in value:
value = value.replace('\x00','')
info_exif[param] = value
except:
pass
return info_exif
def assert_orientation(path_img_origem, path_img_destino):
img = Image.open(path_img_origem)
if not hasattr(img, 'transpose'):
return 0
try:
orientation = int(get_exif(img).get('orientation'))
except:
return 0
transposes = {
1: [],
2: [Image.FLIP_LEFT_RIGHT], # Vertical Mirror
3: [Image.ROTATE_180], # Rotation 180°
4: [Image.FLIP_TOP_BOTTOM], # Horizontal Mirror
5: [Image.FLIP_TOP_BOTTOM, Image.ROTATE_270], # Horizontal Mirror + Rotation 90° CCW
6: [Image.ROTATE_270], # Rotation 270°
7: [Image.FLIP_TOP_BOTTOM, Image.ROTATE_90], # Horizontal Mirror + Rotation 270°
8: [Image.ROTATE_90], # Rotation 90°
}
for transpose in transposes.get(orientation or 1):
img = img.transpose(transpose)
img.save(open(path_img_destino, 'wb'))
return orientation
def detect_orientation(path_img_origem):
img = Image.open(path_img_origem)
try:
orientation = int(get_exif(img).get('orientation'))
except:
orientation = 0
tipo = 'Quadrada'
if img.height > img.width:
tipo = 'Retrato' if orientation in (0, 1, 2, 3, 4) else 'Paisagem'
elif img.height < img.width:
tipo = 'Paisagem' if orientation in (0, 1, 2, 3, 4) else 'Retrato'
return tipo
if __name__ == '__main__':
import requests
for idx in range(1, 9):
arq = '/tmp/landscape_{}.jpg'.format(idx)
arq_new = '/tmp/landscape_{}_new.jpg'.format(idx)
open(arq, 'wb').write(
requests.get(
'https://raw.githubusercontent.com/recurser/'
'exif-orientation-examples/master/Landscape_{}.jpg'.format(idx)
).content,
)
resp = detect_orientation(arq)
assert resp == 'Paisagem'
print(
"%s Orientation: (%s) %s" % (
arq, resp, assert_orientation(arq, arq_new))
)
arq = '/tmp/portrait_{}.jpg'.format(idx)
arq_new = '/tmp/portrait_{}_new.jpg'.format(idx)
open(arq, 'wb').write(
requests.get(
'https://raw.githubusercontent.com/recurser/'
'exif-orientation-examples/master/Portrait_{}.jpg'.format(idx)
).content,
)
resp = detect_orientation(arq)
assert resp == 'Retrato'
print(
"%s Orientation: (%s) %s" % (
arq, resp, assert_orientation(arq, arq_new))
)
assert_orientation(arq, arq_new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment