Javier's Blog

Mostly computers and other tech stuff,...

Thursday, March 13, 2008

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:

Blogger Ross Cadogan said...

Thanks Javier. Works like a charm! :-)

2:00 AM  
Blogger Игорь. said...

You helped me a lot, thanks. :)

* img.size — so simply. Python rulez! (but PIL documentation — definitly not..

11:27 AM  
Anonymous Tony A.A. said...

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.

10:11 PM  

Post a Comment

Links to this post:

Create a Link

<< Home