如何将图像粘贴到另一个图像上,背景的空像素保持为空Python PIL

问题描述 投票:0回答:1

我想将第一张图像(这是一个简单的垂直渐变,从透明到黑色)粘贴到背景的底部。 背景中的空像素需要保持为空,并且必须保留圆角。我知道我需要使用

alpha_composite
paste
masking
的某种组合,但真的无法弄清楚。 我怎样才能使用Python枕头库来实现这一点?

Paste image

Background

Expected result

image-processing python-imaging-library image-masking
1个回答
0
投票

这是一种方法:

#!/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')

© www.soinside.com 2019 - 2024. All rights reserved.