Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent PNG in PIL turns out not to be transparent

Tags:

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) 
like image 815
MarkTraceur Avatar asked Sep 22 '11 06:09

MarkTraceur


People also ask

Why are my PNG files not transparent?

Because when you download the PNG from the Previewer Window, the PNG LOSES the transparency information.

Why does my transparent PNG have a white background?

You can confirm that your file has been converted by pressing edit on the image on your device from the Apple Photos app (see below) If the background turns black then transparency has been maintained. If it stays white then the image has been converted to a JPG file.

Why won't my image save with a transparent background?

You may be used to saving image files for web use as JPEGs, but JPEGs don't support transparent backgrounds. So, instead, you'll need to use a format such as GIF, TIF or, ideally, PNG. The PNG file is small enough for use online but still delivers high quality with transparency as well.


1 Answers

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) 
like image 156
Paul Avatar answered Sep 20 '22 17:09

Paul