我想将第一张图像(这是一个简单的垂直渐变,从透明到黑色)粘贴到背景的底部。 背景中的空像素需要保持为空,并且必须保留圆角。我知道我需要使用
alpha_composite
、paste
和 masking
的某种组合,但真的无法弄清楚。
我怎样才能使用Python枕头库来实现这一点?
这是一种方法:
#!/usr/bin/env python3
from PIL import Image
# Open background and ensure RGBA
bg = Image.open('bg.png').convert('RGBA')
# Open foreground and match to size of background
fg = Image.open('fg.png').resize(bg.size)
# Put aside background alpha channel
bgA = bg.getchannel('A')
# Paste foreground over background with alpha
bg.paste(fg, mask=fg)
# Reapply transparent cut-outs from original background
bg.putalpha(bgA)
bg.save('result.png')