我有一个透明的png图像foo.png,我已经打开了另一个图像:

im = Image.open("foo2.png")

现在我需要合并foo.png和foo2.png。

(foo.png包含一些文本,我想打印该文本在foo2.png)


当前回答

def trans_paste(bg_img,fg_img,box=(0,0)):
    fg_img_trans = Image.new("RGBA",bg_img.size)
    fg_img_trans.paste(fg_img,box,mask=fg_img)
    new_img = Image.alpha_composite(bg_img,fg_img_trans)
    return new_img

其他回答

下面是我的代码,合并2张不同大小的图像,每个都有透明度和偏移量:

from PIL import Image

background = Image.open('image1.png')
foreground = Image.open("image2.png")

x = background.size[0]//2
y = background.size[1]//2

background = Image.alpha_composite(
    Image.new("RGBA", background.size),
    background.convert('RGBA')
)

background.paste(
    foreground,
    (x, y),
    foreground
)

background.show()

这个片段是前面答案的混合,混合元素与偏移,同时处理不同大小的图像,每个图像都具有透明度。

有一个类似的问题,但很难找到答案。下面的函数允许您将带有透明参数的图像粘贴到另一个图像的特定偏移量上。

import Image

def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
    fg_img_trans = Image.new("RGBA",fg_img.size)
    fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
    bg_img.paste(fg_img_trans,box,fg_img_trans)
    return bg_img

bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()

你也可以使用blend:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")

正如olt已经指出的,图像。当源和目标都包含alpha时,粘贴不能正常工作。

考虑以下场景:

两个测试图像,都包含alpha:

layer1 = Image.open("layer1.png")
layer2 = Image.open("layer2.png")

合成图像使用图像。像这样粘贴:

final1 = Image.new("RGBA", layer1.size)
final1.paste(layer1, (0,0), layer1)
final1.paste(layer2, (0,0), layer2)

生成以下图像(覆盖的红色像素的alpha部分完全取自第二层。像素没有正确混合):

合成图像使用图像。Alpha_composite如下所示:

final2 = Image.new("RGBA", layer1.size)
final2 = Image.alpha_composite(final2, layer1)
final2 = Image.alpha_composite(final2, layer2)

生成以下(正确的)图像:

的形象。当背景图像也包含透明度时,粘贴不能像预期的那样工作。你需要使用真正的阿尔法合成。

Pillow 2.0包含一个alpha_composite函数。

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

编辑:两个图像都需要为RGBA类型。所以你需要调用convert('RGBA')如果他们是调色板,等等。如果背景没有alpha通道,那么您可以使用常规的粘贴方法(这应该更快)。