python PIL 不保存透明度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1233772/
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
PIL does not save transparency
提问by Maxim Sloyko
from PIL import Image
img = Image.open('1.png')
img.save('2.png')
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
第一张图片有透明背景,但是当我保存它时,透明度消失了(背景为白色)
What am I doing wrong?
我究竟做错了什么?
回答by Lucas S.
Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.
可能图像已编入索引(PIL 中的模式“P”),因此透明度不是在 PNG alpha 通道中设置的,而是在元数据信息中设置的。
You can get transparent background palette index with the following code:
您可以使用以下代码获取透明背景调色板索引:
from PIL import Image
img = Image.open('1.png')
png_info = img.info
img.save('2.png', **png_info)
image info is a dictionary, so you can inspect it to see the info that it has:
图像信息是一个字典,因此您可以检查它以查看它具有的信息:
eg: If you print it you will get an output like the following:
例如:如果您打印它,您将获得如下输出:
{'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)}
The information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the "transparency" key. In the example it says that palette index "7" must be treated as transparent.
保存在那里的信息会因创建原始 PNG 的工具而异,但这里对您来说重要的是“透明度”键。在示例中,它表示调色板索引“7”必须被视为透明。
回答by Nathan Ross Powell
You can always force the the type to "RGBA",
您始终可以将类型强制为“RGBA”,
img = Image.open('1.png')
img.convert('RGBA')
img.save('2.png')