From 45965112589857ff8891740e4b80b1656e0c284b Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Wed, 20 Nov 2024 21:39:34 +1000 Subject: [PATCH] Clean up background index check --- src/ImageSharp/Formats/Gif/GifEncoderCore.cs | 32 ++++++++++++-------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs index 757b8320dc..0ed7e8c98d 100644 --- a/src/ImageSharp/Formats/Gif/GifEncoderCore.cs +++ b/src/ImageSharp/Formats/Gif/GifEncoderCore.cs @@ -156,12 +156,7 @@ internal sealed class GifEncoderCore frameMetadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex); } - byte backgroundIndex; - if (this.backgroundColor.HasValue) - { - backgroundIndex = GetBackgroundIndex(quantized, this.backgroundColor.Value); - } - else + if (!TryGetBackgroundIndex(quantized, this.backgroundColor, out byte backgroundIndex)) { backgroundIndex = derivedTransparencyIndex >= 0 ? frameMetadata.TransparencyIndex @@ -510,15 +505,19 @@ internal sealed class GifEncoderCore /// /// The current quantized frame. /// The background color to match. + /// The index in the palette of the background color. /// The pixel format. - /// The . - private static byte GetBackgroundIndex(IndexedImageFrame? quantized, Color background) + /// The . + private static bool TryGetBackgroundIndex( + IndexedImageFrame? quantized, + Color? background, + out byte index) where TPixel : unmanaged, IPixel { - int index = -1; - if (quantized != null) + int match = -1; + if (quantized != null && background.HasValue) { - TPixel backgroundPixel = background.ToPixel(); + TPixel backgroundPixel = background.Value.ToPixel(); ReadOnlySpan palette = quantized.Palette.Span; for (int i = 0; i < palette.Length; i++) { @@ -527,12 +526,19 @@ internal sealed class GifEncoderCore continue; } - index = i; + match = i; break; } } - return (byte)Numerics.Clamp(index, 0, 255); + if (match >= 0) + { + index = (byte)Numerics.Clamp(match, 0, 255); + return true; + } + + index = 0; + return false; } ///