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

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

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

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


当前回答

下面是我的代码,合并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()

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

其他回答

你也可以使用blend:

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

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

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

.paste()的第一个参数是要粘贴的图像。第二个是坐标,秘密武器是第三个参数。它指示将用于粘贴图像的掩码。如果你传递一个透明的图像,那么alpha通道被用作蒙版。

检查文档。

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

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通道,那么您可以使用常规的粘贴方法(这应该更快)。

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

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()

下面是我的代码,合并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()

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