PIL:缩略图,并以方形图像结束
调用
image = Image.open(data) image.thumbnail((36,36), Image.NEAREST)
将保持宽高比。 但是我需要最终显示像这样的图像:
<img src="/media/image.png" style="height:36px; width:36px" />
我可以在图像上使用透明或白色的信箱风格吗?
将图像粘贴到具有适当大小的透明图像作为背景
from PIL import Image size = (36, 36) image = Image.open(data) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, (int((size[0] - image.size[0]) / 2), int((size[1] - image.size[1]) / 2)) ) background.save("output.png")
编辑:修正语法错误
PIL已经有一个function来做到这一点:
from PIL import Image, ImageOps thumb = ImageOps.fit(image, size, Image.ANTIALIAS)
from PIL import Image import StringIO def thumbnail_image(): image = Image.open("image.png") image.thumbnail((300, 200)) thumb_buffer = StringIO.StringIO() image.save(thumb_buffer, format=image.format) fp = open("thumbnail.png", "w") fp.write(thumb_buffer.getvalue()) fp.close()
或者,也许…(原谅意大利面条)
from PIL import Image def process_image(image, size): if image.size[0] > size[0] or image.size[1] > size[1]: #preserve original thumb = image.copy() thumb.thumbnail(size,Image.ANTIALIAS) img = thumb.copy() img_padded = Image.new("RGBA",size) img_padded.paste(image,(int((size[0]-image.size[0])/2),int((size[1]-image.size[1])/2))) return img_padded