Created
July 26, 2016 15:17
-
-
Save kellan/4d16848ce7227d1b18218d55295de5b5 to your computer and use it in GitHub Desktop.
square thumbnails with Python PIL (Pillow), make sure to rotate correctly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
from PIL import Image, ExifTags | |
def square_thumb(img, thumb_size): | |
THUMB_SIZE = (thumb_size,thumb_size) | |
exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS) | |
if exif['Orientation'] == 3 : | |
img=img.rotate(180, expand=True) | |
elif exif['Orientation'] == 6 : | |
img=img.rotate(270, expand=True) | |
elif exif['Orientation'] == 8 : | |
img=img.rotate(90, expand=True) | |
width, height = img.size | |
# square it | |
if width > height: | |
delta = width - height | |
left = int(delta/2) | |
upper = 0 | |
right = height + left | |
lower = height | |
else: | |
delta = height - width | |
left = 0 | |
upper = int(delta/2) | |
right = width | |
lower = width + upper | |
img = img.crop((left, upper, right, lower)) | |
img.thumbnail(THUMB_SIZE, Image.ANTIALIAS) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'll save you the pain: Does not add black borders around non-square images.