15
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?

Maxim Sloyko
  • 15,176
  • 9
  • 43
  • 49

2 Answers2

31

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.

Lucas S.
  • 13,391
  • 8
  • 46
  • 46
  • It worked, thank you! Kind of strange, though, that those properties were not saved automatically. – Maxim Sloyko Aug 06 '09 at 06:13
  • This issue still occurs with 32bpp transparent images saved from Photoshop `PNG image data, 1063 x 857, 8-bit/color RGBA, non-interlaced` so there is definitely an issue with PIL. – Orwellophile Feb 20 '22 at 06:20
7

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

img = Image.open('1.png')
img = img.convert('RGBA')
img.save('2.png')
Eduardo Yáñez Parareda
  • 9,126
  • 4
  • 37
  • 50