[Fixed]-Python generate thumbnail with transparancy and fixed width

1๐Ÿ‘

โœ…

I am not sure about sorl-thumbnail but you can do it with Image. You basically need to create a transparent 150ร—150 image and put your thumbnail on top of it.

#!/usr/bin/python

from PIL import Image

margin=20
X=150
Y=150
in_path="flower.jpg"
out_path="thumbnail.png"

#creates a transparent background, RGBA mode, and size 150 by 150.
background = Image.new('RGBA', (X,Y))


# opening an image and converting to RGBA:
img = Image.open(in_path).convert('RGBA')

# Resizing the image

img = img.resize((X, Y-margin*2), Image.ANTIALIAS)

# Putting thumbnail on background

background.paste(img, (0, margin), img)
background.save(out_path)

The output with transparent stripes at the top and bottom:

enter image description here

๐Ÿ‘คAlex Ivanov

Leave a comment