c#byte[] to image error

Scenario: C++ reads the image data into a Byte array and passes it to C#. Error during image restoration of byte[] array. Red is the error location.

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
            System.IO.MemoryStream memory = new System.IO.MemoryStream(data);

           System.Drawing.Image image = System.Drawing.Image.FromStream(memory);

            this.pictureBox1.Image = image;

}


The reasons were found to be as follows:

Image is an abstract class and cannot instantiate objects. You need to use Bitmap, a subclass of Image, and the code is as follows:

        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;

        }

problem solved.

Reference: https://zhidao.baidu.com/question/459415967.html.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325626229&siteId=291194637