Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Alpha channel is discarded when saving an animated PNG #7122

@gsingh93

Description

@gsingh93

What did you do?

Created an animated PNG from RGBA images with transparent colors (non-zero alpha).

What did you expect to happen?

The animated PNG should preserve the alpha channel of the individual images.

What actually happened?

The alpha channel of all but the first image in the sequence is discarded. If the frames are of a static object fading in or out, then PIL then thinks that all of the frames are the same, and then discards them.

This bug also seems to occur with animated GIFs, but I'm not 100% sure the root cause is the same.

What are your OS, Python and Pillow versions?

  • OS: macOS 13.3.1
  • Python: 3.11.3
  • Pillow: 9.5.0

This script will create an APNG from 10 frames, with the alpha of the red square in the center increasing each frame:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

images = []
for i in range(10):
    img = Image.new('RGBA', (300, 300), (255, 255, 255, 255))

    draw = ImageDraw.Draw(img)
    draw.rectangle((100, 100, 200, 200), fill=(255, 0, 0, i * 20))

    img.save(f'frame-{i}.png')
    images.append(img)

images[0].save(
    'test.png', save_all=True, append_images=images[1:], duration=100, loop=0
)
images[0].show()

Here is the PNG file with the transparency issue:
test-incorrect

What happened here is that when the alpha channel was thrown away, all of the images in append_images are exactly the same and they get thrown away.

This is how I would expect the correct image to look:
test-correct

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions