Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import logging
import sys
from PIL import Image, JpegImagePlugin
from PIL.JpegImagePlugin import JpegImageFile
import six
__all__ = [
'ApplyOrientationError',
'Image',
]
log = logging.getLogger(__name__)
def flip_horizontal(im):
return im.transpose(Image.FLIP_LEFT_RIGHT)
def flip_vertical(im):
return im.transpose(Image.FLIP_TOP_BOTTOM)
def rotate_180(im):
return im.transpose(Image.ROTATE_180)
def rotate_90(im):
return im.transpose(Image.ROTATE_90)
def rotate_270(im):
return im.transpose(Image.ROTATE_270)
def transpose(im):
return rotate_90(flip_horizontal(im))
def transverse(im):
return rotate_90(flip_vertical(im))
orientation_funcs = [
None,
lambda x: x,
flip_horizontal,
rotate_180,
flip_vertical,
transpose,
rotate_270,
transverse,
rotate_90,
]
kOrientationEXIFTag = 0x0112
class ApplyOrientationError(Exception):
pass
def apply_orientation(im):
"""
Extract the oritentation EXIF tag from the image, which should be a PIL
Image instance, and if there is an orientation tag that would rotate the
image, apply that rotation to the Image instance given to do an in-place
rotation.
:param Image im: Image instance to inspect
:return: A transposed image instance
Raises ApplyOrientationError if an error occurs
"""
try:
exif = im._getexif()
except AttributeError:
six.reraise(ApplyOrientationError, e, sys.exc_info()[2])
if not exif:
six.reraise(ApplyOrientationError, e, sys.exc_info()[2])
log.debug('EXIF data found')
try:
orientation = exif[kOrientationEXIFTag]
except IndexError:
six.reraise(ApplyOrientationError, e, sys.exc_info()[2])
try:
return orientation_funcs[orientation](im)
except Exception as e:
six.reraise(ApplyOrientationError, e, sys.exc_info()[2])
def save_applied(im, fp, filename):
# encoderinfo gets removed so save it
try:
old_encoderinfo = im.encoderinfo
except AttributeError:
old_encoderinfo = {}
try:
im = apply_orientation(im)
except ApplyOrientationError:
pass
im.encoderinfo = old_encoderinfo
JpegImagePlugin._save(im, fp, filename)
Image.register_save(JpegImageFile.format, save_applied)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.