Imagebox,将字节数组转换为图像,这是怎么回事

本文关键字:图像 怎么回事 数组 字节 字节数 Imagebox 转换 | 更新日期: 2023-09-27 18:24:33

我想制作一个可以从网络摄像头读取数据的应用程序。它使真正明亮的像素变成红色(现在)。但我不能把它写进图像框里。那么问题出在哪里呢?

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    WebCam camera = new WebCam();
    if (!camera.IsConnected())
    {
        camera.Connect();
    }
    else
    {
        Application.Exit();
    }

    //    for (int x = 0; x <= 10000; x++)
    //   {
    camera.Update();
    MemoryStream ms = new MemoryStream();
    camera.CalcBitmap().Save(ms, ImageFormat.Bmp);
    byte[] bitmapData = ms.ToArray();
    /*
                        int i = 54;
                        while (i <= (bitmapData.Length - 2))
                        {
                            if ((bitmapData[i] >= 240) & (bitmapData[i + 1] >= 240) & (bitmapData[i + 2] >= 240))
                            {
                                bitmapData[i] = 255;
                                bitmapData[i + 1] = 0;
                                bitmapData[i + 2] = 0;
                                i += 3;
                            }
                        }*/
    MemoryStream stream = new MemoryStream(bitmapData);
    pictureBox1.Image = new Bitmap(stream);

    //  }
}

Imagebox,将字节数组转换为图像,这是怎么回事

因此,在经历了很多痛苦之后,我将picturebox函数留空,并将所有内容写入了buttonclick函数。它成功了!我仍然不知道问题出在哪里,但我认为即使连接了网络摄像头,picturebox功能也很累。

  public partial class Form1 : Form
{
   public static WebCam camera = new WebCam();
    private void button1_Click(object sender, EventArgs e)
    {
       if (!camera.IsConnected())
            {
                camera.Connect();
                camera.Update();
                MemoryStream ms = new MemoryStream();
                camera.CalcBitmap().Save(ms, ImageFormat.Bmp);
                byte[] bitmapData = ms.ToArray();
                MemoryStream stream = new MemoryStream(bitmapData);
                pictureBox1.Image = new Bitmap(stream);
            }
            else
            {
                Application.Exit();
            }

    }
    public void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
    }

必须对包含非托管资源的对象调用Dispose(),以便释放内存。

MemoryStream ms = null
try{
    //your code
}
finally{
    if(ms != null){
        ms.Dispose()
    }
}