Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL does not save transparency

from PIL import Image

img = Image.open('1.png')
img.save('2.png')

The first image has a transparent background, but when I save it, the transparency is gone (background is white)

What am I doing wrong?

like image 877
Maxim Sloyko Avatar asked Aug 05 '09 14:08

Maxim Sloyko


People also ask

What does save with Transparency mean?

It simply means that you can use any transparent image on your company website and put your main image or logo on it. Similarly, if you use a custom printing site such as PrintShop to print a design on T-shirts, you will send the design with a transparent background.

How do I save a PIL library image?

save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer.


2 Answers

Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.

You can get transparent background palette index with the following code:

from PIL import Image

img = Image.open('1.png')
png_info = img.info
img.save('2.png', **png_info)

image info is a dictionary, so you can inspect it to see the info that it has:

eg: If you print it you will get an output like the following:

{'transparency': 7, 'gamma': 0.45454, 'dpi': (72, 72)}

The information saved there will vary depending on the tool that created the original PNG, but what is important for you here is the "transparency" key. In the example it says that palette index "7" must be treated as transparent.

like image 62
Lucas S. Avatar answered Sep 30 '22 08:09

Lucas S.


You can always force the the type to "RGBA",

img = Image.open('1.png')
img.convert('RGBA')
img.save('2.png')
like image 41
Nathan Ross Powell Avatar answered Sep 30 '22 08:09

Nathan Ross Powell