I have a transparent png image "foo.png" and I've opened another image with
im = Image.open("foo2.png");
now what i need is to merge foo.png with foo2.png.
( foo.png contains some text and I want to print that text on foo2.png )
And what about bitmap images? PNG-24 supports only GIF-like transparency (one color is specified to be the transparent color and it is fully transparent). PNG-32 supports different levels of transparency via the alpha channel, in which each pixel can have an opacity between 0 and 255.
Firstly we opened the primary image and saved its image object into variable img1. Then we opened the image that would be used as an overlay and saved its image object into variable img2. Then we called the paste method to overlay/paste the passed image on img1.
from PIL import Image background = Image.open("test1.png") foreground = Image.open("test2.png") background.paste(foreground, (0, 0), foreground) background.show()
First parameter to .paste()
is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.
Check the docs.
Image.paste
does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.
Pillow 2.0 contains an alpha_composite
function that does this.
background = Image.open("test1.png") foreground = Image.open("test2.png") Image.alpha_composite(background, foreground).save("test3.png")
EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA')
if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With