PIL:缩略图并以方形图像结束 [英] PIL: Thumbnail and end up with a square image

查看:38
本文介绍了PIL:缩略图并以方形图像结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打电话

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?

推荐答案

将图片粘贴成大小合适的透明图片作为背景

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.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:缩略图并以方形图像结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆