@@ -150,9 +150,6 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
150150 this . SanitizeAndSetEncoderOptions < TPixel > ( this . encoder , pngMetadata , out this . use16Bit , out this . bytesPerPixel ) ;
151151
152152 stream . Write ( PngConstants . HeaderBytes ) ;
153- this . WriteHeaderChunk ( stream ) ;
154- this . WriteGammaChunk ( stream ) ;
155- this . WriteColorProfileChunk ( stream , metadata ) ;
156153
157154 ImageFrame < TPixel > ? clonedFrame = null ;
158155 ImageFrame < TPixel > currentFrame = image . Frames . RootFrame ;
@@ -164,9 +161,13 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
164161 ClearTransparentPixels ( currentFrame ) ;
165162 }
166163
164+ // Do not move this. We require an accurate bit depth for the header chunk.
167165 IndexedImageFrame < TPixel > ? quantized = this . CreateQuantizedImageAndUpdateBitDepth ( pngMetadata , currentFrame , null ) ;
168- this . WritePaletteChunk ( stream , quantized ) ;
169166
167+ this . WriteHeaderChunk ( stream ) ;
168+ this . WriteGammaChunk ( stream ) ;
169+ this . WriteColorProfileChunk ( stream , metadata ) ;
170+ this . WritePaletteChunk ( stream , quantized ) ;
170171 this . WriteTransparencyChunk ( stream , pngMetadata ) ;
171172 this . WritePhysicalChunk ( stream , metadata ) ;
172173 this . WriteExifChunk ( stream , metadata ) ;
0 commit comments