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

查看:106
本文介绍了如何使用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将仅使用网络安全色,结果看起来会很糟糕.
  • 我正在为图像添加透明度信息.
  • The mask is now inverted. The white was replaced with black and vice versa.
  • I'm converting into 'P' with an 'adaptive' palette. Otherwise, PIL will only use web-safe colors and the result will look bad.
  • I'm adding transparency info to the image.

请注意:这种方法存在很大的问题.如果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天全站免登陆