@@ -133,6 +133,9 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
133133 Guard . NotNull ( image , nameof ( image ) ) ;
134134 Guard . NotNull ( stream , nameof ( stream ) ) ;
135135
136+ // Stream may not at 0.
137+ long basePosition = stream . Position ;
138+
136139 Configuration configuration = image . Configuration ;
137140 ImageMetadata metadata = image . Metadata ;
138141 BmpMetadata bmpMetadata = metadata . GetBmpMetadata ( ) ;
@@ -187,7 +190,7 @@ public void Encode<TPixel>(Image<TPixel> image, Stream stream, CancellationToken
187190
188191 this . WriteBitmapInfoHeader ( stream , infoHeader , buffer , infoHeaderSize ) ;
189192 this . WriteImage ( configuration , stream , image ) ;
190- WriteColorProfile ( stream , iccProfileData , buffer ) ;
193+ WriteColorProfile ( stream , iccProfileData , buffer , basePosition ) ;
191194
192195 stream . Flush ( ) ;
193196 }
@@ -271,16 +274,20 @@ private BmpInfoHeader CreateBmpInfoHeader(int width, int height, int infoHeaderS
271274 /// <param name="stream">The stream to write to.</param>
272275 /// <param name="iccProfileData">The color profile data.</param>
273276 /// <param name="buffer">The buffer.</param>
274- private static void WriteColorProfile ( Stream stream , byte [ ] ? iccProfileData , Span < byte > buffer )
277+ /// <param name="basePosition">The Stream may not be start with 0.</param>
278+ private static void WriteColorProfile ( Stream stream , byte [ ] ? iccProfileData , Span < byte > buffer , long basePosition )
275279 {
276280 if ( iccProfileData != null )
277281 {
278282 // The offset, in bytes, from the beginning of the BITMAPV5HEADER structure to the start of the profile data.
279283 int streamPositionAfterImageData = ( int ) stream . Position - BmpFileHeader . Size ;
280284 stream . Write ( iccProfileData ) ;
285+ long position = stream . Position ; // Storage Position
281286 BinaryPrimitives . WriteInt32LittleEndian ( buffer , streamPositionAfterImageData ) ;
282- stream . Position = BmpFileHeader . Size + 112 ;
287+ _ = stream . Seek ( basePosition , SeekOrigin . Begin ) ;
288+ _ = stream . Seek ( BmpFileHeader . Size + 112 , SeekOrigin . Current ) ;
283289 stream . Write ( buffer [ ..4 ] ) ;
290+ _ = stream . Seek ( position , SeekOrigin . Begin ) ; // Reset Position
284291 }
285292 }
286293
0 commit comments