comparison core/image.py @ 837:234726f5a47a

For issue #74, re-orient uploaded images if necessary.
author Brian Neal <bgneal@gmail.com>
date Sat, 04 Oct 2014 13:43:22 -0500
parents ee87ea74d46b
children 36d988b800c2
comparison
equal deleted inserted replaced
836:1e44691932b2 837:234726f5a47a
39 elif h > w: 39 elif h > w:
40 diff = (h - w) / 2 40 diff = (h - w) / 2
41 image = image.crop((0, diff, w, h - diff)) 41 image = image.crop((0, diff, w, h - diff))
42 image = image.resize((size, size), Image.ANTIALIAS) 42 image = image.resize((size, size), Image.ANTIALIAS)
43 return image 43 return image
44
45
46 # Various image transformation functions:
47 def flip_horizontal(im):
48 return im.transpose(Image.FLIP_LEFT_RIGHT)
49
50 def flip_vertical(im):
51 return im.transpose(Image.FLIP_TOP_BOTTOM)
52
53 def rotate_180(im):
54 return im.transpose(Image.ROTATE_180)
55
56 def rotate_90(im):
57 return im.transpose(Image.ROTATE_90)
58
59 def rotate_270(im):
60 return im.transpose(Image.ROTATE_270)
61
62 def transpose(im):
63 return rotate_90(flip_horizontal(im))
64
65 def transverse(im):
66 return rotate_90(flip_vertical(im))
67
68 # From http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
69 # EXIF Orientation tag values:
70 # 1 = Horizontal (normal)
71 # 2 = Mirror horizontal
72 # 3 = Rotate 180
73 # 4 = Mirror vertical
74 # 5 = Mirror horizontal and rotate 270 CW
75 # 6 = Rotate 90 CW
76 # 7 = Mirror horizontal and rotate 90 CW
77 # 8 = Rotate 270 CW
78
79 ORIENT_FUNCS = {
80 2: flip_horizontal,
81 3: rotate_180,
82 4: flip_vertical,
83 5: transpose,
84 6: rotate_270,
85 7: transverse,
86 8: rotate_90,
87 }
88
89 ORIENT_TAG = 0x112
90
91
92 def orient_image(im):
93 """Transforms the given image according to embedded EXIF data.
94
95 The image instance, im, should be a PIL Image.
96 If there is EXIF information for the image, and the orientation tag
97 indicates that the image should be transformed, perform the transformation.
98
99 Returns a tuple of the form (flag, image) where flag is True if the image
100 was oriented and False otherwise. image is either a new transformed image or
101 the original image instance.
102
103 """
104 if hasattr(im, '_getexif'):
105 exif = im._getexif()
106 if exif and ORIENT_TAG in exif:
107 return (True, ORIENT_FUNCS[ORIENT_TAG](im))
108
109 return (False, im)