使用 PIL/Pillow 将透明图像粘贴到背景上

0 python png python-imaging-library

我试图使图像部分透明,然后将其叠加在第二个图像上。例如,获取此图像并将其透明度设置为 50%,然后将其粘贴到此图像上以创建此合成图像。我尝试使用以下代码来做到这一点:

from PIL import Image

background = Image.open("one.png")
foreground = Image.open("circle.png")
foreground.putalpha(120) # Sets the oval to 50% transparency
background.paste(foreground, (0, 0)) # Paste oval over the background
background.show()
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试这个时,它只显示前景。是否可以通过这种方式使用 PIL/Pillow 调整透明度以获得所需的合成图像?

小智 5

我不知道“putalpha”是如何工作的,但是对于将 png 图像与透明背景重叠的类似问题,我刚刚在课程中学到的是,png 图像也必须是蒙版。像这样:

from PIL import Image

background = Image.open("one.png")
foreground = Image.open("circle.png")
foreground.putalpha(120) # Sets the oval to 50% transparency
background.paste(foreground, (0, 0),mask=foreground) 
# Paste oval over the background
# use oval as mask
background.show()
Run Code Online (Sandbox Code Playgroud)