Vinod Maurya Vinod Maurya - 1 year ago 163
C# Question

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

I am trying to convert a

in c#. Following is the code:

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

It shows the error
Parameter is not valid
when creating the

byte[] b
is coming from a network stream.

But when I write this byte[] to a file, and open this file in any image viewer just works perfectly. Following is code for writing the byte[] to file:

var fs = new BinaryWriter(new FileStream("tmp.bmp", FileMode.Create, FileAccess.Write));

What am I missing here?


Here is my full code that was causing problem

Socket s = listener.AcceptSocket();
byte[] b = new byte[imgLen];
MemoryStream ms = new MemoryStream(b);
// now here I am using ms.Seek(0, SeekOrigin.Begin); that fixed my problem.
Bitmap bmp = new Bitmap(ms);
pictureBox1.Image = bmp;

I am using this code on
event and there is nothing extra. I am just trying to display an Image that is streamed on network. The server is written in Java that is streaming this image.

Hope it clarifies the doubts.


Answer Source

Try resetting current location in the stream

MemoryStream ms = new MemoryStream(b);
ms.Seek(0, SeekOrigin.Begin);
Bitmap bmp = new Bitmap(ms);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download