views:

417

answers:

1

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?

+11  A: 

Paste the image into a transparent image with the right size as a background

from PIL import Image
size = (36, 36)
image = Image.open(data)
image.thumbnail(size, Image.NEAREST)
background = Image.new('RGBA', size, (255, 255, 255, 0))
background.paste(
    image,
    ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))

EDIT: fixed syntax error

Nadia Alramli