Transparent PNG in PIL turns out not to be transparent

MarkTraceur picture MarkTraceur · Sep 22, 2011 · Viewed 16.7k times · Source

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)

Answer

Paul picture Paul · Sep 22, 2011

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)