PIL : PNG 图像作为 JPG 图像的水印

PIL : PNG image as watermark for a JPG image

我正在尝试从 JPEG 照片 (1600x900) 和带有 Alpha 通道 (400x62) 的 PNG 徽标制作合成图像。

这是一个用图像魔法完成工作的命令:

composite -geometry +25+25 watermark.png original_photo.jpg watermarked_photo.jpg

现在我想在 python 脚本中执行类似的操作,而无需使用 PIL 从外部调用此 shell 命令。

这是我尝试过的:

photo = Image.open('original_photo.jpg')
watermark = Image.open('watermark.png')
photo.paste(watermark, (25, 25))

这里的问题是 alpha 通道被完全忽略,结果就像我的水印是黑白的,而不是 rbga(0, 0, 0, 0)rbga(255, 255, 255, 128)

确实,PIL docs state:"See alpha_composite() if you want to combine images with respect to their alpha channels."

所以我看了alpha_composite()。不幸的是,此功能要求两个图像具有相同的大小和模式。

最后,我仔细阅读Image.paste(),发现:

If a mask is given, this method updates only the regions indicated by the mask. You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.

所以我尝试了以下方法:

photo = Image.open('original_photo.jpg')
watermark = Image.open('watermark.png')
photo.paste(watermark, (25, 25), watermark)

而且...它成功了!