问题
I'm trying to make a composite image from a JPEG photo (1600x900) and a PNG logo with alpha channel (400x62).
Here is a command that does the job with image magick:
composite -geometry +25+25 watermark.png original_photo.jpg watermarked_photo.jpg
Now I'd like to do something similar in a python script, without invoking this shell command externally, with PIL.
Here is what I tried :
photo = Image.open('original_photo.jpg')
watermark = Image.open('watermark.png')
photo.paste(watermark, (25, 25))
The problem here is that the alpha channel is completely ignored and the result is as if my watermark were black and white rather than rbga(0, 0, 0, 0)
and rbga(255, 255, 255, 128)
.
Indeed, PIL docs state : "See alpha_composite() if you want to combine images with respect to their alpha channels."
So I looked at alpha_composite()
. Unfortunately, this function requires both images to be of the same size and mode.
回答1:
Eventually, I read Image.paste() more carefully and found this out:
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.
So I tried the following :
photo = Image.open('original_photo.jpg')
watermark = Image.open('watermark.png')
photo.paste(watermark, (25, 25), watermark)
And... it worked!
来源:https://stackoverflow.com/questions/43708681/pil-png-image-as-watermark-for-a-jpg-image