Pillow icon indicating copy to clipboard operation
Pillow copied to clipboard

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

Open kumquat-ir opened this issue 1 year ago • 2 comments

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.

kumquat-ir avatar Feb 09 '24 05:02 kumquat-ir

I've created PR #7788 to resolve this.

radarhere avatar Feb 09 '24 08:02 radarhere

Can confirm that PR fixes it, probably the best solution since a delta with a solid color, unchanging background isnt gonna be less data than the original frame.

kumquat-ir avatar Feb 09 '24 21:02 kumquat-ir