Skip to content

Commit

Permalink
Clean up background index check
Browse files Browse the repository at this point in the history
  • Loading branch information
JimBobSquarePants committed Nov 20, 2024
1 parent b4567a4 commit 4596511
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions src/ImageSharp/Formats/Gif/GifEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
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
Expand Down Expand Up @@ -510,15 +505,19 @@ private static int GetTransparentIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
/// </summary>
/// <param name="quantized">The current quantized frame.</param>
/// <param name="background">The background color to match.</param>
/// <param name="index">The index in the palette of the background color.</param>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <returns>The <see cref="byte"/>.</returns>
private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quantized, Color background)
/// <returns>The <see cref="bool"/>.</returns>
private static bool TryGetBackgroundIndex<TPixel>(
IndexedImageFrame<TPixel>? quantized,
Color? background,
out byte index)
where TPixel : unmanaged, IPixel<TPixel>
{
int index = -1;
if (quantized != null)
int match = -1;
if (quantized != null && background.HasValue)
{
TPixel backgroundPixel = background.ToPixel<TPixel>();
TPixel backgroundPixel = background.Value.ToPixel<TPixel>();
ReadOnlySpan<TPixel> palette = quantized.Palette.Span;
for (int i = 0; i < palette.Length; i++)
{
Expand All @@ -527,12 +526,19 @@ private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
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;
}

/// <summary>
Expand Down

0 comments on commit 4596511

Please sign in to comment.