设置图像的alpha值(通过PIL / Pillow)

2024-04-20 16:40:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张底图,在上面,我试着用50%的alpha粘贴一条黑色条带。我一直在测试的是:

from PIL import Image, ImageFont, ImageDraw

base_width, base_height = base_img.size
if base_img.mode != 'RGB':
    base_img = base_img.convert("RGB")
black_strip = Image.new('RGBA', (base_width, 20),(0,0,0,128)) #creating the black strip
offset = (0,base_height/2)
base_img.paste(background,offset)

生成的黑色条带没有alpha透明度;它是完全实心的。示例:

enter image description here

有人能帮我改进一下吗?在


Tags: fromimagealphaimgbase粘贴rgbwidth
1条回答
网友
1楼 · 发布于 2024-04-20 16:40:09

正如您所注意到的,Image.paste忽略了粘贴图像的alpha通道。但是,它确实需要一个可选的mask参数。这将接受RGBA图像作为输入,提取其alpha通道,因此您应该能够再次传入粘贴的图像:

base_img.paste(black_strip, offset, black_strip)

这也使得在原始图像没有遮罩的情况下很容易生成遮罩。例如,以下操作将粘贴RGB图像,但使其黑色区域透明:

^{pr2}$

PS以上建议仅在基础图像没有alpha通道(其模式为RGB,而不是RGBA)时有效。否则,您可能应该使用Image.alpha_composite来组合图像,尽管令人恼火的是,您可能首先必须填充或裁剪粘贴的图像,使其与基本图像的大小相同。在

相关问题 更多 >