Vinod Maurya Vinod Maurya - 24 days ago 23
C# Question

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

I am trying to convert a

byte[]
to
Bitmap
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
Bitmap
.

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));
fs.Write(b);
fs.Close();


What am I missing here?

EDIT

Here is my full code that was causing problem

Socket s = listener.AcceptSocket();
byte[] b = new byte[imgLen];
s.Receive(b);
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;
s.Close();


I am using this code on
Form_Load
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.

Thanks

Answer

Try resetting current location in the stream

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