如何更改图像的不透明度并与 Python 中的另一个图像合并

How to change opacity of image and merge with another image in Python

我一直在寻找如何将两张图片放在一起,将最上面的一张调整为大约 50% 的透明度。

到目前为止,我设法找到了这个:

from PIL import Image

def merge():
    background = Image.open("ib.jpg")
    background = background .convert('L') #only foreground color matters
    foreground = Image.open("if.jpg")

    background.paste(foreground, (0, 0), foreground)
    background.show()

但它只输出一张空白图像。

两者尺寸相同。

ib.jpg:

if.jpg:

期望的输出:

关于使用 RGB 或 RGBA 文件执行此操作的任何提示?我应该处理这两种类型(实际上,有些有 alpha 层)。

谢谢,

您必须使用 PIL.Image 中的 blend 函数:

from PIL import Image
bg = Image.open("1.jpg")
fg = Image.open("2.jpg")
# set alpha to .7
Image.blend(bg, fg, .7).save("out.png")