Skip to content

Setting disposal=2 on gif export can cause issues with transparency #7787

@kumquat-ir

Description

@kumquat-ir

What did you do?

Created a sequence of images with jittering text and saved them as a gif, specifying disposal=2

What did you expect to happen?

The gif to correctly display the images, with a consistent background

What actually happened?

The background flashes between opaque and transparent, with which frames are which depending on how exactly the text is jittering
testout

What are your OS, Python and Pillow versions?

  • OS: Linux (Arch)
  • Python: 3.11.6
  • Pillow: 10.2.0

This code with these images was used to generate the above gif:

from PIL import Image

baseimage = Image.open("test0.png")
images = [
    Image.open("test1.png")
]
baseimage.save("testout.gif", save_all=True, append_images=images, loop=0, duration=1000, disposal=2)

test0.png:
test0
test1.png:
test1

As far as I can tell, this is occurring because of the optimization in #7568 depending on a delta image which, when disposal is 2, can have been generated with a background image that is filled with a color with a palette index that does not exist in the frame's palette, presumably creating a nonsense delta.
Moving these lines of code outside the if statement seems to fix the issue, presumably due to _get_background having a side effect of placing the appropriate color into the frame's palette with the same index as in the background.
This does not occur when disposal is set to any other value or when optimize is set to False due to skipping one or both of the codepaths involved in the bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions