场景:C++读取图像数据转成Byte数组,传递给C#。在byte[]数组图像复原时报错。红色为出错位置。
private void button3_Click(object sender, EventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(memory);
this.pictureBox1.Image = image;
}
经查找发现原因如下:
Image是抽象类,不能实例化对象。需要使用Image的子类Bitmap,代码如下:
private void button3_Click(object sender, EventArgs e)
{
int width = 652, heiht = 484;
byte[] data = new byte[width * heiht * 3];// data.lengh = 949608
int back = GetData(data);
int len = data.Length;// len = 946704
Bitmap img = new Bitmap(652, 484, PixelFormat.Format24bppRgb);
BitmapData data1 = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
System.Runtime.InteropServices.Marshal.Copy(data, 0, data1.Scan0, data.Length);
img.UnlockBits(data1);
this.pictureBox1.Image = img;
}
问题解决。
参考:https://zhidao.baidu.com/question/459415967.html。