Skip to content

Commit 4596511

Browse files
Clean up background index check
1 parent b4567a4 commit 4596511

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

src/ImageSharp/Formats/Gif/GifEncoderCore.cs

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
156156
frameMetadata.TransparencyIndex = ClampIndex(derivedTransparencyIndex);
157157
}
158158

159-
byte backgroundIndex;
160-
if (this.backgroundColor.HasValue)
161-
{
162-
backgroundIndex = GetBackgroundIndex(quantized, this.backgroundColor.Value);
163-
}
164-
else
159+
if (!TryGetBackgroundIndex(quantized, this.backgroundColor, out byte backgroundIndex))
165160
{
166161
backgroundIndex = derivedTransparencyIndex >= 0
167162
? frameMetadata.TransparencyIndex
@@ -510,15 +505,19 @@ private static int GetTransparentIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
510505
/// </summary>
511506
/// <param name="quantized">The current quantized frame.</param>
512507
/// <param name="background">The background color to match.</param>
508+
/// <param name="index">The index in the palette of the background color.</param>
513509
/// <typeparam name="TPixel">The pixel format.</typeparam>
514-
/// <returns>The <see cref="byte"/>.</returns>
515-
private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quantized, Color background)
510+
/// <returns>The <see cref="bool"/>.</returns>
511+
private static bool TryGetBackgroundIndex<TPixel>(
512+
IndexedImageFrame<TPixel>? quantized,
513+
Color? background,
514+
out byte index)
516515
where TPixel : unmanaged, IPixel<TPixel>
517516
{
518-
int index = -1;
519-
if (quantized != null)
517+
int match = -1;
518+
if (quantized != null && background.HasValue)
520519
{
521-
TPixel backgroundPixel = background.ToPixel<TPixel>();
520+
TPixel backgroundPixel = background.Value.ToPixel<TPixel>();
522521
ReadOnlySpan<TPixel> palette = quantized.Palette.Span;
523522
for (int i = 0; i < palette.Length; i++)
524523
{
@@ -527,12 +526,19 @@ private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
527526
continue;
528527
}
529528

530-
index = i;
529+
match = i;
531530
break;
532531
}
533532
}
534533

535-
return (byte)Numerics.Clamp(index, 0, 255);
534+
if (match >= 0)
535+
{
536+
index = (byte)Numerics.Clamp(match, 0, 255);
537+
return true;
538+
}
539+
540+
index = 0;
541+
return false;
536542
}
537543

538544
/// <summary>

0 commit comments

Comments
 (0)