首页 > 解决方案 > 如何在普通图像上粘贴半透明图像并获得透明度 PIL?

问题描述

所以我试图在普通图像上粘贴一个透明图像。但是由于某种原因,透明度消失了。

有没有办法将第二张图像(透明图像)的透明度保持在第一张图像(普通图像)之上,而不会失去第二张图像的透明度?

(顺便说一下,我是 PIL 的新手)

BG = Image.open("BGImage.png") # normal image, size is 1920x1080
BG = BG.convert("RGBA")
overlay = Image.open("OverlayImage.png") # transparent image, size is 1920x1080
overlay = overlay.convert("RGBA")

BG = Image.alpha_composite(BG, overlay) # I tried doing this but it didn't work

BG.save("NewImage.png")

背景图片: 背景

叠加图像: 覆盖

我得到了什么: 我得到了什么

我想要的(颜色略有变化): 我想要的

标签: pythonpython-3.ximagepython-imaging-library

解决方案


像这样使用paste- 在确保您的图像没有被调色后

from PIL import Image

# Open background and foreground ensuring they are not palette images
bg = Image.open('bg.png').convert('RGB')
fg = Image.open('fg.png')

# Paste foreground onto background and save
bg.paste(fg,mask=fg)
bg.save('result.png')

在此处输入图像描述


推荐阅读