Python PIL:如何使PNG中的区域透明?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4379978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:30:02  来源:igfitidea点击:

Python PIL: how to make area transparent in PNG?

pythonimagepngtransparencypython-imaging-library

提问by Hoff

I've been using PIL to crop Images, now I also want to make certain rectangular areas transparent, say

我一直在使用 PIL 来裁剪图像,现在我也想让某些矩形区域透明,比如

from PIL import Image
im = Image.open("sample.png")
transparent_area = (50,80,100,200)
...

I'd really appreciate some code as I haven't been able to find it, thanks a lot in advance!

我真的很感激一些代码,因为我找不到它,非常感谢!

Cheers,

干杯,

Hoff

霍夫

采纳答案by unutbu

from PIL import Image
from PIL import ImageDraw
im = Image.open("image.png")
transparent_area = (50,80,100,200)

mask=Image.new('L', im.size, color=255)
draw=ImageDraw.Draw(mask) 
draw.rectangle(transparent_area, fill=0)
im.putalpha(mask)
im.save('/tmp/output.png')

I learned how to do this here.

在这里学会了如何做到这一点

回答by kindall

No source code, but this is the general approach that should work: Create an alpha channel for the image in "L" (grayscale) mode as a separate image object. Fill the alpha channel with white (full opacity) and draw the rectangle on the alpha channel image in black (full transparency). Convert the image to which you want to apply the transparency to RGBA and use the image object putalpha()method to copy the alpha channel you created into the image's alpha channel. Save as PNG.

没有源代码,但这是应该起作用的一般方法:在“L”(灰度)模式下为图像创建一个 alpha 通道作为单独的图像对象。用白色(完全不透明)填充 Alpha 通道,并用黑色(完全透明)在 Alpha 通道图像上绘制矩形。将要应用透明度的图像转换为 RGBA,并使用图像对象putalpha()方法将您创建的 alpha 通道复制到图像的 alpha 通道中。另存为 PNG。