Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL : PNG image as watermark for a JPG image

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.

like image 676
Antoine Pinsard Avatar asked Apr 30 '17 16:04

Antoine Pinsard


People also ask

How do I make a PNG a watermark?

Press and hold down the ALT key, then type the numbers 0169 on your number keypad. Release ALT, and the copyright symbol should appear. Add text to the copyright symbol if you want the copyright watermark to include more information.

How do I display an image using PIL?

Import the module Image from PIL. Create a variable img and then call the function open() in it. Give the path that has the image file. Call the show() function in joint with img variable through the dot operator “.”.


1 Answers

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!

like image 142
Antoine Pinsard Avatar answered Nov 03 '22 00:11

Antoine Pinsard