Skip to content

Instantly share code, notes, and snippets.

@kellan
Created July 26, 2016 15:17
Show Gist options
  • Save kellan/4d16848ce7227d1b18218d55295de5b5 to your computer and use it in GitHub Desktop.
Save kellan/4d16848ce7227d1b18218d55295de5b5 to your computer and use it in GitHub Desktop.
square thumbnails with Python PIL (Pillow), make sure to rotate correctly
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
@yspreen
Copy link

yspreen commented Dec 29, 2018

I'll save you the pain: Does not add black borders around non-square images.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment