Byte array for bitmap

I did this code to get the image and convert it to a bitmap, but it does not 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; } 

He receives:

 Bitmap bmp = new Bitmap(imagestream); 

And gives me this error:

Invalid parameter

+5
source share
4 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); 
+8
source

You probably are not getting enough bytes in stream.read(data,0,data.length) , because Read does not guarantee that it will read data.length bytes. you need to check its return value and continue reading until reading data.length .

See: Stream.Read method return value

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

PS: I assume that length and Read are typos.

+1
source

I assume that you have a table and you want to get the image from the database.

 int cout = ds.Tables["TableName"].Rows.Count; if (cout > 0) { if (ds.Tables["TableName"].Rows[cout - 1]["Image"] != DBNull.Value) { var data = (byte[])(ds.Tables["TableName"].Rows[cout - 1]["Image"]); var stream = new MemoryStream(data); pictureBox1.Image = Image.FromStream(stream); } else { pictureBox1.Image = null; } } 
0
source

Try the following:

 int size = BitConverter.ToInt32(data.Reverse().ToArray(),0); 
-one
source

All Articles