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

Arackna picture Arackna · Mar 16, 2011 · Viewed 124.5k times · Source

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 )

Answer

nosklo picture nosklo · Mar 16, 2011
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.