使 png 图像透明

Making a png image transparent

提问人:M Protik 提问时间:11/15/2023 最后编辑:9769953M Protik 更新时间:11/15/2023 访问量:47

问:

如果我想使 .png 图像透明,我不能

blue = Image.open(image_path + "blue_color.png")
blue.putalpha(100)

但是如果我这样做

blue = blue.convert('RGBA')

现在我可以让它透明了。

我只是想知道我用这段代码做什么

.convert('RGBA')

在此处输入图像描述

蟒蛇 python-imaging-library

评论

0赞 Mark Setchell 11/15/2023
为什么你不能运行你的前 2 行代码?会发生什么?他们应该工作正常。
0赞 Mark Setchell 11/23/2023
你已经很安静了。你是怎么接受这些建议的?

答:

0赞 Hassan Safari 11/15/2023 #1
blue.putalpha(100)

putalpha 是从 0 到 255,它定义了背景的透明度 但首先你必须将你的图像作为 PNG 引入,所以你必须对编译器说我的图像是 RGBA,它有一个 Alpha(红、绿、蓝、ALPHA(透明度))

2赞 Mahboob Nur 11/15/2023 #2
blue = blue.convert('RGBA')

Python 图像库 (PIL) 中的 convert 方法 Pillow 用于更改图像模式。对于 PNG 图像,有时模式可能未设置为“RGBA”(红色、绿色、蓝色、Alpha),其中包括用于透明度的 Alpha 通道。

1赞 Mark Setchell 11/15/2023 #3

你没有理由不能做你想做的事情。有多种方法可以从 RGB 图像转换为 RGBA 图像。我将展示两种方法,用水平线分隔。


from PIL import Image

# Create 64x64 RGB image in blue
RGB = Image.new('RGB', (64,64), 'blue')

# Convert mode to RGBA
RGBA = RGB.convert('RGBA')

print(RGBA)

输出

图像现在是 RGBA:

<PIL.Image.Image image mode=RGBA size=64x64>

from PIL import Image

# Create 64x64 RGB image in blue
im = Image.new('RGB', (64,64), 'blue')

# Push in an alpha channel, forcing mode change from RGB to RGBA
im.putalpha(32)

print(im)

输出:

图像已强制从 RGB 转换为 RGBA:

<PIL.Image.Image image mode=RGBA size=64x64>