如何使用 PIL 生成圆形缩略图? [英] How do I generate circular thumbnails with PIL?

查看:46
本文介绍了如何使用 PIL 生成圆形缩略图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PIL 生成圆形图像缩略图?圆圈外的空间应该是透明的.

How do I generate circular image thumbnails using PIL? The space outside the circle should be transparent.

非常感谢您提供片段,在此先感谢您.

Snippets would be highly appreciated, thank you in advance.

推荐答案

最简单的方法是使用掩码.创建具有您想要的任何形状的黑白蒙版.并使用 putalpha 将该形状作为 alpha 层:

The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And use putalpha to put that shape as an alpha layer:

from PIL import Image, ImageOps

mask = Image.open('mask.png').convert('L')
im = Image.open('image.png')

output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)

output.save('output.png')

这是我使用的面具:

如果您希望缩略图大小可变,您可以使用 ImageDraw 并绘制蒙版:

If you want the thumbnail size to be variable you can use ImageDraw and draw the mask:

from PIL import Image, ImageOps, ImageDraw

size = (128, 128)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask) 
draw.ellipse((0, 0) + size, fill=255)

im = Image.open('image.jpg')

output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)

output.save('output.png')

<小时>

如果你想以 GIF 格式输出,那么你需要使用粘贴功能而不是 putalpha:

from PIL import Image, ImageOps, ImageDraw

size = (128, 128)
mask = Image.new('L', size, 255)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=0)

im = Image.open('image.jpg')

output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.paste(0, mask=mask)
output.convert('P', palette=Image.ADAPTIVE)

output.save('output.gif', transparency=0)

请注意,我做了以下更改:

Note that I did the following changes:

  • 面具现在被反转了.白色被替换为黑色,反之亦然.
  • 我正在使用自适应"调色板转换为P".否则,PIL 将只使用网络安全颜色,结果看起来很糟糕.
  • 我正在为图片添加透明度信息.

请注意:这种方法存在一个大问题.如果 GIF 图像包含黑色部分,它们也将全部变为透明.您可以通过为透明度选择另一种颜色来解决此问题.我强烈建议您为此使用 PNG 格式.但如果你不能,那是你能做的最好的.

Please note: There is a big issue with this approach. If the GIF image contained black parts, all of them will become transparent as well. You can work around this by choosing another color for the transparency. I would strongly advise you to use PNG format for this. But if you can't then that is the best you could do.

这篇关于如何使用 PIL 生成圆形缩略图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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