Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge a transparent png image with another image using PIL

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 )

like image 328
Arackna Avatar asked Mar 16 '11 11:03

Arackna


People also ask

Can a .PNG file can contain transparency in an image?

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.

How do you overlay an image on another image in Python?

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.


2 Answers

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.

like image 71
nosklo Avatar answered Sep 28 '22 03:09

nosklo


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).

like image 24
olt Avatar answered Sep 28 '22 05:09

olt