Python生成具有透明度和固定宽度的缩略图

时间:2015-06-24 14:56:32

标签: python django python-2.7 sorl-thumbnail

所以我尝试使用Python / Django sorl-thumbnail库生成缩略图,并且我被要求生成一个150x150的图像,就像这样(如果你不能看到顶部有一些透明的边距在底部:

Image to generate

我试着这样做:

get_thumbnail(
            original_image, '150x150', quality=99, format='PNG'
        )

我可以用sorl-thumbnail吗?我的意思是在顶部和底部添加透明胶片,并将整个图像尺寸保持在150x150?如果不是我怎么能用另一个python包实现这个呢?

感谢

1 个答案:

答案 0 :(得分:1)

我不确定sorl-thumbnail但你可以用Image做到。您基本上需要创建一个透明的150x150图像并将缩略图放在它上面。

#!/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)

顶部和底部带有透明条纹的输出:

enter image description here