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 Comments:
Thanks Javier. Works like a charm! :-)
You helped me a lot, thanks. :)
* img.size — so simply. Python rulez! (but PIL documentation — definitly not..
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.
Post a Comment
Links to this post:
Create a Link
<< Home