32

I have been hitting my head against the wall for a while with this, so maybe someone out there can help.

I'm using PIL to open a PNG with transparent background and some random black scribbles, and trying to put it on top of another PNG (with no transparency), then save it to a third file.

It comes out all black at the end, which is irritating, because I didn't tell it to be black.

I've tested this with multiple proposed fixes from other posts. The image opens in RGBA format, and it's still messed up.

Also, this program is supposed to deal with all sorts of file formats, which is why I'm using PIL. Ironic that the first format I tried is all screwy.

Any help would be appreciated. Here's the code:

from PIL import Image
img = Image.open(basefile)
layer = Image.open(layerfile) # this file is the transparent one
print layer.mode # RGBA
img.paste(layer, (xoff, yoff)) # xoff and yoff are 0 in my tests
img.save(outfile)
Juuso Ohtonen
  • 8,826
  • 9
  • 65
  • 98
MarkTraceur
  • 323
  • 1
  • 3
  • 7
  • Possible duplicate of http://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil – Charles Merriam Aug 24 '15 at 01:28

1 Answers1

54

I think what you want to use is the paste mask argument. see the docs, (scroll down to paste)

from PIL import Image
img = Image.open(basefile)
layer = Image.open(layerfile) # this file is the transparent one
print layer.mode # RGBA
img.paste(layer, (xoff, yoff), mask=layer) 
# the transparancy layer will be used as the mask
img.save(outfile)
Jonathan Root
  • 535
  • 2
  • 14
  • 31
Paul
  • 42,322
  • 15
  • 106
  • 123
  • 4
    Bravo! The PIL documentation wasn't clear on what the mask was--first I thought it was a number (because they said something like 'if the mask is 0, if the mask is 255'), then I thought it was like the box argument, but instead was used to determine which part of the image argument would be copied. Now it makes more sense, thanks! – MarkTraceur Sep 22 '11 at 16:20
  • You helped me very much. Thank you – imkost Mar 05 '13 at 01:37
  • @Claudiu, oh why on earth indeed. – Ray May 16 '16 at 10:16