Fix GIF transparency handling and dither
Merged
JI
4mo ago+120+120+012345678901234567890123456789-16-16-01234567890123456789
Prerequisites
- I have written a descriptive pull-request title
- I have verified that there are no overlapping pull-requests open
- I have verified that I am following the existing coding patterns and practice as demonstrated in the repository. These follow strict Stylecop rules :cop:.
- I have provided test coverage for my change (where applicable)
Description
Fixes #3142
This pull request improves GIF encoding and palette handling, especially for animated images with transparency. It ensures fully transparent pixels are properly treated during dithering and quantization, fixes issues where transparent indices were not always reserved, and adds tests for a previously failing edge case (issue #3142). The changes also introduce a transparent color to the Werner palette for better compatibility.
GIF Transparency and Palette Handling Improvements:
- Ensured a transparent color is always present in the Werner palette to support transparency in palette-based images. (
src/ImageSharp/Color/Color.WernerPalette.cs) - Updated GIF encoding logic to always reserve a transparent index for additional frames when required, even if the entire frame matches the previous one, preventing placeholder pixels from being mapped to opaque colors. (
src/ImageSharp/Formats/Gif/GifEncoderCore.cs) [1] [2] [3] [4] [5] [6] - Improved dithering processors to skip error diffusion for fully transparent pixels, preserving exact transparency and avoiding accidental color shifts that could break transparency in indexed images. (
src/ImageSharp/Processing/Processors/Dithering/ErrorDither.cs,src/ImageSharp/Processing/Processors/Dithering/OrderedDither.cs) [1] [2]
Testing and Regression Coverage:
- Added a regression test and reference output for issue #3142, ensuring the encoder correctly handles animated GIFs with full transparency and placeholder frames. (
tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs,tests/ImageSharp.Tests/TestImages.cs,tests/Images/External/ReferenceOutput/GifEncoderTests/GifEncoder_CanDecode_AndEncode_Issue3142_Rgba32_issue_3142.gif/*) [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13]
Test Suite Improvements:
- Enabled an animated GIF visual test for easier validation of animated encoding results. (
tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs) - Added missing using directive for
SixLabors.ImageSharp.Processingto support new test cases. (tests/ImageSharp.Tests/Formats/Gif/GifEncoderTests.cs)