Parameter is not valid error when creating image from byte[] in c#

Okay, just to clarify things a bit... the problem is that new Bitmap(ms) is going to read the data from the stream's current position - if the stream is currently positioned at the end of the data, it's not going to be able to read anything, hence the problem.

The question claims that the code is this:

MemoryStream ms = new MemoryStream(b);
Bitmap bmp = new Bitmap(ms);

In that case there is no requirement to reset the position of the stream, as it will be 0 already. However, I suspect the code is actually more like this:

MemoryStream ms = new MemoryStream();
// Copy data into ms here, e.g. reading from NetworkStream
Bitmap bmp = new Bitmap(ms);

or possibly:

MemoryStream ms = new MemoryStream(b);
// Other code which *reads* from ms, which will change its position,
// before we finally call the constructor:
Bitmap bmp = new Bitmap(ms);

In this case you do need to reset the position, because otherwise the "cursor" of the stream is at the end of the data instead of the start. Personally, however, I prefer using the Position property instead of the Seek method, just for simplicity, so I'd use:

MemoryStream ms = new MemoryStream();
// Copy data into ms here, e.g. reading from NetworkStream

// Rewind the stream ready for reading
ms.Position = 0;
Bitmap bmp = new Bitmap(ms);

It just goes to show how important it is that the sample code in a question is representative of the actual code...


Try resetting current location in the stream

MemoryStream ms = new MemoryStream(b);
ms.Seek(0, SeekOrigin.Begin);
Bitmap bmp = new Bitmap(ms);

Tags:

C#

Image