字节数组到位图图像
我制作此代码以接收图像并将其转换为位图图像,但它不起作用。
这是代码:
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; }
它得到:
Bitmap bmp = new Bitmap(imagestream);
并给我这个错误:
参数无效
这是一种替代方法
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);
您可能没有在stream.read(data,0,data.length)
接收到足够的字节,因为Read
不能确保它将读取data.length
个字节。 你必须检查它的返回值并继续读取直到data.Length
字节被读取。
请参阅: Stream.Read方法的返回值
int read = 0; while (read != data.Length) { read += stream.Read(data, read, data.Length - read); }
PS:我假设length
s并且read
s是拼写错误。
我假设你有一张桌子,想要从数据库接收图片。
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; } }
试试这个:
int size = BitConverter.ToInt32(data.Reverse().ToArray(),0);