Fix Python – How to merge a transparent png image with another image using PIL

Question

Asked By – Arackna

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 )

Now we will see solution for issue: How to merge a transparent png image with another image using PIL


Answer

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.

This question is answered By – nosklo

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0