@@ -261,6 +261,58 @@ public Image<TPixel> Decode<TPixel>(Stream stream)
261261 }
262262 }
263263
264+ /// <summary>
265+ /// Detects the image pixel size from the specified stream.
266+ /// </summary>
267+ /// <param name="stream">The <see cref="Stream"/> containing image data.</param>
268+ /// <returns>The color depth, in number of bits per pixel</returns>
269+ public int DetectPixelSize ( Stream stream )
270+ {
271+ this . currentStream = stream ;
272+ this . currentStream . Skip ( 8 ) ;
273+ try
274+ {
275+ PngChunk currentChunk ;
276+ while ( ! this . isEndChunkReached && ( currentChunk = this . ReadChunk ( ) ) != null )
277+ {
278+ try
279+ {
280+ switch ( currentChunk . Type )
281+ {
282+ case PngChunkTypes . Header :
283+ this . ReadHeaderChunk ( currentChunk . Data ) ;
284+ this . ValidateHeader ( ) ;
285+ this . isEndChunkReached = true ;
286+ break ;
287+ case PngChunkTypes . End :
288+ this . isEndChunkReached = true ;
289+ break ;
290+ }
291+ }
292+ finally
293+ {
294+ // Data is rented in ReadChunkData()
295+ if ( currentChunk . Data != null )
296+ {
297+ ArrayPool < byte > . Shared . Return ( currentChunk . Data ) ;
298+ }
299+ }
300+ }
301+ }
302+ finally
303+ {
304+ this . scanline ? . Dispose ( ) ;
305+ this . previousScanline ? . Dispose ( ) ;
306+ }
307+
308+ if ( this . header == null )
309+ {
310+ throw new ImageFormatException ( "PNG Image hasn't header chunk" ) ;
311+ }
312+
313+ return this . CalculateBitsPerPixel ( ) ;
314+ }
315+
264316 /// <summary>
265317 /// Converts a byte array to a new array where each value in the original array is represented by the specified number of bits.
266318 /// </summary>
@@ -343,6 +395,28 @@ private void InitializeImage<TPixel>(ImageMetaData metadata, out Image<TPixel> i
343395 this . scanline = Buffer < byte > . CreateClean ( this . bytesPerScanline ) ;
344396 }
345397
398+ /// <summary>
399+ /// Calculates the correct number of bits per pixel for the given color type.
400+ /// </summary>
401+ /// <returns>The <see cref="int"/></returns>
402+ private int CalculateBitsPerPixel ( )
403+ {
404+ switch ( this . pngColorType )
405+ {
406+ case PngColorType . Grayscale :
407+ case PngColorType . Palette :
408+ return this . header . BitDepth ;
409+ case PngColorType . GrayscaleWithAlpha :
410+ return this . header . BitDepth * 2 ;
411+ case PngColorType . Rgb :
412+ return this . header . BitDepth * 3 ;
413+ case PngColorType . RgbWithAlpha :
414+ return this . header . BitDepth * 4 ;
415+ default :
416+ throw new NotSupportedException ( "Unsupported PNG color type" ) ;
417+ }
418+ }
419+
346420 /// <summary>
347421 /// Calculates the correct number of bytes per pixel for the given color type.
348422 /// </summary>
0 commit comments