天天看點

C# 調用AForge類庫操作攝像頭

很多都是C#調用window API 發送SendMessage,實作操作攝像頭,但是C#調用window API的時候因為驅動的問題,總是彈出視訊選擇對話框,讓人很是無語,看到大牛們有的截獲到了window消息,然後模拟點選确定按鈕,這是在是不敢恭維啊,還有的大牛根據API原型重寫了,至于我是一隻IT小小鳥了,然後在繼續百度,找到了一個AForge強大的C#類庫,最後終于搞定了,接下來将我拙劣的代碼部分貼出來,以便同行或者需要的朋友學習交流,

首先用到AForge類庫下載下傳位址:http://www.aforgenet.com/

然後引用AForge,AForge.Controls(這個是控件,可以添加到工具箱中),AForge.Imaging,AForge.Video,AForge.Video.DirectShow;

然後直接上代碼

private FilterInfoCollection videoDevices;

private VideoCaptureDevice videoSource;

public int selectedDeviceIndex = 0;

下面是擷取裝置

public FilterInfoCollection GetDevices()

        {

            try

            {

                //枚舉所有視訊輸入裝置

                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count != 0)

                {

                    LogClass.WriteFile("已找到視訊裝置.");

                    return videoDevices;

                }

                else

                    return null;

            }

            catch (Exception ex)

                LogClass.WriteFile("error:沒有找到視訊裝置!具體原因:" + ex.Message);

                return null;

        }

選擇裝置,然後連接配接攝像頭

<p> /// <summary>

        /// 連接配接視訊攝像頭

        /// </summary>

        /// <param name="deviceIndex"></param>

        /// <param name="resolutionIndex"></param>

        /// <returns></returns>

        public VideoCaptureDevice VideoConnect(int deviceIndex = 0, int resolutionIndex = 0)

            if (videoDevices.Count <= 0)

            selectedDeviceIndex = deviceIndex;

            videoSource = new VideoCaptureDevice(videoDevices[deviceIndex].MonikerString);</p><p>            return videoSource;

        }</p>

//抓圖,拍照,單幀

public void GrabBitmap(string path)

{

if (videoSource == null)

return;

g_Path = path;

videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);

}

void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)

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

string fullPath = path + "temp\\";

if (!Directory.Exists(fullPath))

Directory.CreateDirectory(fullPath);

string img = fullPath + DateTime.Now.ToString("yyyyMMdd hhmmss") + ".bmp";

bmp.Save(img);

//如果這裡不寫這個,一會兒會不停的拍照,

videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame);

這樣就完成了操作攝像頭的工作