PIL: Thumbnail and end up with a square image

Paul Tarjan picture Paul Tarjan · Sep 6, 2009 · Viewed 32.1k times · Source

Calling

image = Image.open(data)
image.thumbnail((36,36), Image.NEAREST)

will maintain the aspect ratio. But I need to end up displaying the image like this:

<img src="/media/image.png" style="height:36px; width:36px" />

Can I have a letterbox style with either transparent or white around the image?

Answer

Cesar Canassa picture Cesar Canassa · Dec 12, 2011

PIL already has a function to do exactly that:

from PIL import Image, ImageOps
thumb = ImageOps.fit(image, size, Image.ANTIALIAS)