Browse Source

Clean up background index check

pull/2842/head
James Jackson-South 2 years ago
parent
commit
4596511258
  1. 32
      src/ImageSharp/Formats/Gif/GifEncoderCore.cs

32
src/ImageSharp/Formats/Gif/GifEncoderCore.cs

@ -156,12 +156,7 @@ internal sealed class GifEncoderCore
frameMetadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex); frameMetadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex);
} }
byte backgroundIndex; if (!TryGetBackgroundIndex(quantized, this.backgroundColor, out byte backgroundIndex))
if (this.backgroundColor.HasValue)
{
backgroundIndex = GetBackgroundIndex(quantized, this.backgroundColor.Value);
}
else
{ {
backgroundIndex = derivedTransparencyIndex >= 0 backgroundIndex = derivedTransparencyIndex >= 0
? frameMetadata.TransparencyIndex ? frameMetadata.TransparencyIndex
@ -510,15 +505,19 @@ internal sealed class GifEncoderCore
/// </summary> /// </summary>
/// <param name="quantized">The current quantized frame.</param> /// <param name="quantized">The current quantized frame.</param>
/// <param name="background">The background color to match.</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> /// <typeparam name="TPixel">The pixel format.</typeparam>
/// <returns>The <see cref="byte"/>.</returns> /// <returns>The <see cref="bool"/>.</returns>
private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quantized, Color background) private static bool TryGetBackgroundIndex<TPixel>(
IndexedImageFrame<TPixel>? quantized,
Color? background,
out byte index)
where TPixel : unmanaged, IPixel<TPixel> where TPixel : unmanaged, IPixel<TPixel>
{ {
int index = -1; int match = -1;
if (quantized != null) if (quantized != null && background.HasValue)
{ {
TPixel backgroundPixel = background.ToPixel<TPixel>(); TPixel backgroundPixel = background.Value.ToPixel<TPixel>();
ReadOnlySpan<TPixel> palette = quantized.Palette.Span; ReadOnlySpan<TPixel> palette = quantized.Palette.Span;
for (int i = 0; i < palette.Length; i++) for (int i = 0; i < palette.Length; i++)
{ {
@ -527,12 +526,19 @@ internal sealed class GifEncoderCore
continue; continue;
} }
index = i; match = i;
break; 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> /// <summary>

Loading…
Cancel
Save