@@ -156,12 +156,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
156
156
frameMetadata . TransparencyIndex = ClampIndex ( derivedTransparencyIndex ) ;
157
157
}
158
158
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 ) )
165
160
{
166
161
backgroundIndex = derivedTransparencyIndex >= 0
167
162
? frameMetadata . TransparencyIndex
@@ -510,15 +505,19 @@ private static int GetTransparentIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
510
505
/// </summary>
511
506
/// <param name="quantized">The current quantized frame.</param>
512
507
/// <param name="background">The background color to match.</param>
508
+ /// <param name="index">The index in the palette of the background color.</param>
513
509
/// <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 )
516
515
where TPixel : unmanaged, IPixel < TPixel >
517
516
{
518
- int index = - 1 ;
519
- if ( quantized != null )
517
+ int match = - 1 ;
518
+ if ( quantized != null && background . HasValue )
520
519
{
521
- TPixel backgroundPixel = background . ToPixel < TPixel > ( ) ;
520
+ TPixel backgroundPixel = background . Value . ToPixel < TPixel > ( ) ;
522
521
ReadOnlySpan < TPixel > palette = quantized . Palette . Span ;
523
522
for ( int i = 0 ; i < palette . Length ; i ++ )
524
523
{
@@ -527,12 +526,19 @@ private static byte GetBackgroundIndex<TPixel>(IndexedImageFrame<TPixel>? quanti
527
526
continue ;
528
527
}
529
528
530
- index = i ;
529
+ match = i ;
531
530
break ;
532
531
}
533
532
}
534
533
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 ;
536
542
}
537
543
538
544
/// <summary>
0 commit comments