@@ -380,18 +380,42 @@ private IndexedImageFrame<TPixel> QuantizeAdditionalFrameAndUpdateMetadata<TPixe
380
380
// We can use the color data from the decoded metadata here.
381
381
// We avoid dithering by default to preserve the original colors.
382
382
ReadOnlyMemory < Color > palette = metadata . LocalColorTable . Value ;
383
-
384
383
if ( hasDuplicates && ! metadata . HasTransparency )
385
384
{
386
- // A difference was captured but the metadata does not have transparency.
385
+ // Duplicates were captured but the metadata does not have transparency.
387
386
metadata . HasTransparency = true ;
388
- transparencyIndex = palette . Length ;
389
- metadata . TransparencyIndex = ClampIndex ( transparencyIndex ) ;
390
- }
391
387
392
- PaletteQuantizer quantizer = new ( palette , new ( ) { Dither = null } , transparencyIndex ) ;
393
- using IQuantizer < TPixel > frameQuantizer = quantizer . CreatePixelSpecificQuantizer < TPixel > ( this . configuration , quantizer . Options ) ;
394
- quantized = frameQuantizer . BuildPaletteAndQuantizeFrame ( encodingFrame , bounds ) ;
388
+ if ( palette . Length < 256 )
389
+ {
390
+ // We can use the existing palette and set the transparent index as the length.
391
+ // decoders will ignore this value.
392
+ transparencyIndex = palette . Length ;
393
+ metadata . TransparencyIndex = ClampIndex ( transparencyIndex ) ;
394
+
395
+ PaletteQuantizer quantizer = new ( palette , new ( ) { Dither = null } , transparencyIndex ) ;
396
+ using IQuantizer < TPixel > frameQuantizer = quantizer . CreatePixelSpecificQuantizer < TPixel > ( this . configuration , quantizer . Options ) ;
397
+ quantized = frameQuantizer . BuildPaletteAndQuantizeFrame ( encodingFrame , bounds ) ;
398
+ }
399
+ else
400
+ {
401
+ // We must quantize the frame to generate a local color table.
402
+ IQuantizer quantizer = this . hasQuantizer ? this . quantizer ! : KnownQuantizers . Octree ;
403
+ using IQuantizer < TPixel > frameQuantizer = quantizer . CreatePixelSpecificQuantizer < TPixel > ( this . configuration , quantizer . Options ) ;
404
+ quantized = frameQuantizer . BuildPaletteAndQuantizeFrame ( encodingFrame , bounds ) ;
405
+
406
+ // The transparency index derived by the quantizer will differ from the index
407
+ // within the metadata. We need to update the metadata to reflect this.
408
+ int derivedTransparencyIndex = GetTransparentIndex ( quantized , null ) ;
409
+ metadata . TransparencyIndex = ClampIndex ( derivedTransparencyIndex ) ;
410
+ }
411
+ }
412
+ else
413
+ {
414
+ // Just use the local palette.
415
+ PaletteQuantizer quantizer = new ( palette , new ( ) { Dither = null } , transparencyIndex ) ;
416
+ using IQuantizer < TPixel > frameQuantizer = quantizer . CreatePixelSpecificQuantizer < TPixel > ( this . configuration , quantizer . Options ) ;
417
+ quantized = frameQuantizer . BuildPaletteAndQuantizeFrame ( encodingFrame , bounds ) ;
418
+ }
395
419
}
396
420
else
397
421
{
0 commit comments