3

I have a bunch of images I need to put a text-overlay on top of. I created the overlay with GIMP (PNG with transparency) and tried pasting it on top of the other image:

from PIL import Image

background = Image.open("hahn_echo_1.png")
foreground = Image.open("overlay_step_3.png")

background.paste(foreground, (0, 0), foreground)
background.save("abc.png")

However, instead of displaying a nice black text on top, I get this:

Broken Image

overlay.png looks like this in Gimp:

Overlay Gimp

So I would expect some nice and black text instead of this colorful mess.

Any ideas? Some PIL option I am missing?

martineau
  • 119,623
  • 25
  • 170
  • 301
user3696412
  • 1,321
  • 3
  • 15
  • 33

1 Answers1

5

As vrs pointed out above, using alpha_composite like this answer: How to merge a transparent png image with another image using PIL

does the trick. Make sure to have the images in the correct mode (RGBA).

Complete solution:

from PIL import Image

background = Image.open("hahn_echo_1.png").convert("RGBA")
foreground = Image.open("overlay_step_3.png").convert("RGBA")
print(background.mode)
print(foreground.mode)

Image.alpha_composite(background, foreground).save("abc.png")

Result:

Result

Community
  • 1
  • 1
user3696412
  • 1,321
  • 3
  • 15
  • 33
  • 2
    It sure looks like a palette problem - GIMP can't handle indexed PNG images with partial transparence - so, I'd say OP's background image is an indexed.png and PIL is forcing the overlay to indexed in a wrong way when pasting with `.paste`. I'd say that simply applying the `.convert` step on teh background would work for the OP. – jsbueno Jan 04 '16 at 13:18