如何使用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的方法是使用面具。 创建一个具有任何您想要的形状的黑白蒙版。 并使用
putalpha
将该形状作为 alpha 图层:这是我使用的蒙版:
如果您希望缩略图大小可变,您可以使用
ImageDraw
并绘制遮罩:如果您想要 GIF 格式的输出,则需要使用粘贴功能而不是
putalpha
code>:请注意,我做了以下更改:
被替换为黑色,反之亦然。
请注意:这种方法存在一个大问题。 如果 GIF 图像包含黑色部分,则所有黑色部分也会变成透明。 您可以通过选择另一种透明度颜色来解决此问题。
我强烈建议您使用 PNG 格式。 但如果你做不到,那就是你能做的最好的事情了。
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:Here is the mask I used:
If you want the thumbnail size to be variable you can use
ImageDraw
and draw the mask:If you want the output in GIF then you need to use the paste function instead of
putalpha
:Note that I did the following changes:
was replaced with black and vice versa.
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.
我想在已经接受的答案中添加一个对结果圆进行抗锯齿的解决方案,技巧是生成一个更大的掩模,然后使用抗锯齿过滤器将其缩小:
代码。
在我看来,这是产生更好结果的
I would like to add to the already accepted answer a solution to antialias the resulting circle, the trick is to produce a bigger mask and then scale it down using an ANTIALIAS filter:
here is the code
this produces a far better result in my opinion.
对@DRC 的解决方案进行轻微修改,以支持已经具有透明度的图像。 他将圆外的 Alpha 通道设置为 0(不可见),将圆内设置为 255(不透明),因此我使用
darker
来获取蒙版和原始 Alpha 的 min频道(可以是 0-255 之间的任意数字):-)Slight modification on @DRC's solution to also support images which already have transparency. He sets the alpha channel to 0 (invisible) outside the circle and to 255 inside (opaque), so I use
darker
which takes the min of the mask and the original alpha channel (which can be anywhere betwen 0-255) :-)非常感谢。 我花了几个小时寻找,你的想法成功了。
与那里的其他脚本一起。
PIL 圆边并添加边框
它非常适合我。
将此图像命名为 AceOfSpades.png 用于测试
Thank you very much. I was looking for hours and your idea does the trick.
Together with this other script from there.
PIL round edges and add border
it works perfectly for me.
Name this image AceOfSpades.png for testing