Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte Array to Bitmap Image

I made this code to receive an image and convert it to bitmap image but it doesn't work.

Here is the code:

public void ReceiveImage()
{
    NetworkStream stream = new NetworkStream(socket);
    byte[] data = new byte[4];
    stream.read(data,0,data.length,0)
    int size = BitConverter.ToInt32(data,0);
    data = new byte[size];
    stream.read(data,0,data.length)
    MemoryStream imagestream = new MemoryStream(data);
    Bitmap bmp = new Bitmap(imagestream);
    picturebox1.Image = bmp;
}

It gets to:

Bitmap bmp = new Bitmap(imagestream);

And gives me this error:

Parameter is not valid

like image 230
Tarek Adel Avatar asked Jul 30 '12 22:07

Tarek Adel


2 Answers

This is an alternative method

int w= 100;
int h = 200;
int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case)

byte[] imageData    = new byte[w*h*ch]; //you image data here
Bitmap bitmap       = new Bitmap(w,h,PixelFormat.Format24bppRgb);
BitmapData bmData   = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr pNative      = bmData.Scan0;
Marshal.Copy(imageData,0,pNative,w*h*ch);
bitmap.UnlockBits(bmData);
like image 74
morishuz Avatar answered Oct 11 '22 23:10

morishuz


You are probably not receiving enough bytes in stream.read(data,0,data.length) since Read does not ensure that it will read data.length bytes. you have to check its return value and continue to read till data.Length bytes are read.

See : Stream.Read Method's return value

int read = 0;
while (read != data.Length)
{
    read += stream.Read(data, read, data.Length - read);
}

PS: I am assuming lengths and reads are typos.

like image 37
L.B Avatar answered Oct 12 '22 01:10

L.B