gpt4 book ai didi

python - PIL : PNG image as watermark for a JPG image

转载 作者:太空狗 更新时间:2023-10-29 21:18:07 67 4
gpt4 key购买 nike

我正在尝试从 JPEG 照片 (1600x900) 和带有 alpha channel (400x62) 的 PNG Logo 制作合成图像。

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

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

现在我想在 python 脚本中做一些类似的事情,而不用从外部调用这个 shell 命令,使用 PIL。

这是我尝试过的:

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

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

确实,PIL docs state :“如果你想根据图像的 alpha channel 组合图像,请参见 alpha_composite()。”

所以我查看了 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)

而且...它成功了!

关于python - PIL : PNG image as watermark for a JPG image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708681/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com