天天看點

在WPF中使用AForge.net控制攝像頭拍照

利用AForge.net控制攝像頭拍照最友善的方法就是利用PictureBox顯示攝像頭畫面,但在WPF中不能直接使用PictureBox。必須通過<WindowsFormsHost></WindowsFormsHost>來提供交換功能。其解決方法如下:

1、按照正常方法建立一個WPF應用程式;

2、添加引用

WindowsFormsIntegration  (與WinForm互動的支援)

System.Windows.Forms (WinForm控件支援)

AForge.Video和AForge.Video.DirectShow(拷貝AForge.Video.dll,AForge.Video.DirectShow.dll,攝像頭操作的庫)

3、在XAML中添加  xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"(用wf代替System.Windows.Forms,即可使用<wf:PictureBox/>添加PictureBox控件

4、在界面相應位置添加

<WindowsFormsHost Name="winForm">

  <wf:PictureBox Name="myPicture"/>

</WindowsFormsHost>(至此,界面層的設定完成)

5、代碼部分

首先在視窗加載時初始化攝像頭

 myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;

            FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (videoDevices.Count <= 0)

            {

                System.Windows.MessageBox.Show("請連接配接攝像頭");

                return;

            }

            else

                CloseCaptureDevice();

                myCaptureDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);//myCaptureDevice的類型為VideoCaptureDevice,

                myCaptureDevice.NewFrame += new NewFrameEventHandler(myCaptureDevice_NewFrame);

                myCaptureDevice.DesiredFrameSize = new System.Drawing.Size(436, 360);//436, 360

                myCaptureDevice.DesiredFrameRate = 10;

                myCaptureDevice.Start();                

PictureBox myPhoto = pictureHost.Child as System.Windows.Forms.PictureBox;//擷取界面中的myPicture控件

void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)//幀處理程式

        {

            Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();

            myPhoto.Image = bitmap.Clone(

                new RectangleF((bitmap.Size.Width - 295) / 2, (bitmap.Size.Height - 413) / 2, 295, 413), //顯示圖像的寬度為295像素,高度為413像素

                System.Drawing.Imaging.PixelFormat.Format32bppRgb);

        }

關閉攝像頭,釋放系統資源(在視窗推出時必須調用)

 private void CloseCaptureDevice()

            if (myCaptureDevice != null)

                if (myCaptureDevice.IsRunning)

                {

                    myCaptureDevice.SignalToStop();                   

                }

       myCaptureDevice = null;

    }

至此,使用AForge.net操作攝像頭基本完成。攝像頭捕獲的畫面能在PictureBox中顯示出來,如果要實作拍照隻需使用myCaptureDevice.Stop()停止攝像頭,儲存PictureBox中的Image屬性即可。

原來想直接使用WPF中的Image控件顯示攝像頭,但在幀處理程式中始終提示無法操作幀圖像,提示:沒有權限操作,另一程序擁有該對象(大概是這個意思)。在這個問題上我糾結了大概有10天,一直都沒有找到解決的辦法,還請高人指點,謝謝!!