Square thumbnail with Python Image Library

Every once in a while someone will walk up to me and ask, “how do you make a square thumbmail using PIL (Python Image Library)”? To this I say:


import Image

THUMB_SIZE = 80, 80
img = Image.open("someimge.jpg")
width, height = img.size

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)
img.save("someimge-thumb.jpg")

They usually walk away satisfied…

3 thoughts on “Square thumbnail with Python Image Library

  1. This was helpful. Thanks! In my case, I didn't use the "thumbnail" function, so it may be worth pointing out that it's optional. The reason was that I wanted to stretch image if originals were too small, so they don't mess up my design.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.