如何更改PIL中矩形的不透明度?

2024-06-26 00:06:34 发布

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

我正试图实现类似下图的效果,使用半透明的黑框,上面写着:Desired

忽略这一事实,它们是不同的图像,但我想实现类似于上图的半透明矩形效果。我目前拥有的代码是:

from PIL import Image, ImageDraw

img = Image.new('RGBA', (512, 512), (255, 0, 0, 0))
draw = ImageDraw.Draw(img, 'RGBA')
shape = [(0, 512), (512, 308)]
draw.rectangle(shape, fill = 'black')

img.save('foo.png')


img2 = Image.open('final2.png')


Image.alpha_composite(img2, img).save('foo3.png')

这将产生以下输出:

Output(忽略白色边框-这只是一个粗略的屏幕截图)

我试过putalpha,但它只是使黑色矩形变成灰色,仍然不透明。此外,我还尝试创建一个透明图像,其大小与我希望在其上绘制长方体的图像(512x512)相同,然后在该透明图像的底部绘制一个矩形,然后使用“混合”,但图像的颜色混乱,因为白色图像在顶部混合

感谢您的帮助

编辑:仍然需要帮助


Tags: 图像imageimgpngsave绘制img2draw
1条回答
网友
1楼 · 发布于 2024-06-26 00:06:34

请注意在将来提供输入、输出和预期输出图像。我将以下文本覆盖在透明背景上,并添加了洋红色边框,以便您可以看到其范围:

enter image description here

然后我将您的代码改写为:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Create new solid red background
h, w = 400, 600
bg = Image.new('RGB', (w, h), (255, 0, 0))

# Create copy and make bottom part black
dark = bg.copy()
draw  = ImageDraw.Draw(dark)
draw.rectangle((0, int(0.7*h), w, h), 0)
dark.save('dark.png')   # DEBUG

# Blend darkened copy over top of background
blended = Image.blend(bg, dark, 0.8) 
blended.save('blended.png')   # DEBUG

# Load text overlay with transparent background, paste on top and save
overlay = Image.open('text.png').convert('RGBA')
blended.paste(overlay, mask=overlay)
blended.save('result.png')

这就产生了这样的结果:

enter image description here

相关问题 更多 >