public void CreateBitmap(Image img) { if (pictureBox1.InvokeRequired)//调用和创建该控件的线程是不同的线程,必须调用Invoke方法 { if (close) { return; } //创建该方法的委托实例 SetBitmapCallback d = new SetBitmapCallback(CreateBitmap); //调用该委托实例,并传递参数,参数为object类型,使用this调用Invoke(this为当前窗体,是创建该窗体控件的线程) Invoke(d, new object[] { img });//this指定创建该控件的线程来Invoke(调用) } else//调用与创建该控件的线程是同一个线程 { if (img != null) { Bitmap bitmap = new Bitmap(img); if (process) { BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int success = FaceApi.DrawFaces(bitmapData.Scan0, bitmapData.Width, bitmapData.Height, bitmapData.Stride, 3); bitmap.UnlockBits(bitmapData); if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } pictureBox1.BackgroundImage = bitmap; } else { if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } pictureBox1.BackgroundImage = bitmap; } } else { if (pictureBox1.BackgroundImage != null) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = null; } } } }
private void button2_Click(object sender, EventArgs e) { if (pictureBox1.BackgroundImage != null) { Bitmap bitmap = new Bitmap(image); BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int success = FaceApi.DrawFaces(bitmapData.Scan0, bitmapData.Width, bitmapData.Height, bitmapData.Stride, 3); bitmap.UnlockBits(bitmapData); if (success == 0) { pictureBox1.BackgroundImage.Dispose(); pictureBox1.BackgroundImage = bitmap; } else { bitmap.Dispose(); MessageBox.Show("绘制人脸失败!"); } } else { MessageBox.Show("请添加图片!"); } }