Imagesharp: Decoding failes with memory stream at EOF

Created on 7 Jan 2017  路  2Comments  路  Source: SixLabors/ImageSharp

Hi,
decoding from a memory stream fails if the stream position is already at EOF.
In example:

Stream zipStream = ... // get a zipped jpeg
MemoryStream unzippedStream = new MemoryStream();
await zipStream.CopyToAsync(unzippedStream);
Image image = new Image(unzippedStream); 

Code above fails with a NotSupportedException "Image cannot be loaded. Available formats: ..." because Image.Decode() find an empty header (Image{TColor].cs line 447) calling stream.Read() at EOF.

The following works:

Stream zipStream = ... // get a zipped jpeg
MemoryStream unzippedStream = new MemoryStream();
await zipStream.CopyToAsync(unzippedStream); 

unzippedStream.Position = 0;  // add this to reset stream position

Image image = new Image(unzippedStream); 

I think Image constructor should set Stream.Position = 0 when decoding images from streams.

wontfix

Most helpful comment

I disagree. The image constructor should not move the position.

The reason why this would be a bad choice for us to make is for compatibility with streams that don't allow setting the position at all, network streams are a good example, basically any form of forward only, read only streams.

In my experience (for this exact reason) it has always been the responsibility of the caller to make sure a stream is at the correct position.

All 2 comments

I disagree. The image constructor should not move the position.

The reason why this would be a bad choice for us to make is for compatibility with streams that don't allow setting the position at all, network streams are a good example, basically any form of forward only, read only streams.

In my experience (for this exact reason) it has always been the responsibility of the caller to make sure a stream is at the correct position.

@corradolab Agree with @tocsoft. Moving the position of a stream inside the decoder goes against the best practices.

Just imagine the case, when the caller has a stream, where the image data is starting somewhere in the middle, and moves Position to the right place before decoding.

Was this page helpful?
0 / 5 - 0 ratings