C#調用攝像頭實現拍照功能的示例代碼
前言
老師要求我們學生做一套拍照身份驗證系統,經過長時間的學習,有了這篇文章,希望能幫到讀者們。
正文
首先介紹本文的主角:AForge
創(chuàng)建一個C#項目,引用必備的幾個DLL
- AForge.dll
- AForge.Controls.dll
- AForge.Imaging.dll
- AForge.Math.dll
- AForge.Video.DirectShow.dll
- AForge.Video.dll
這些DLL讀者們可以在文末下載我附帶的Demon
引用必要的命名空間
using AForge.Controls; using AForge.Video; using AForge.Video.DirectShow;
至此,便可以開始編寫代碼了。
首先遍歷操作系統上的攝像頭控件:
public static bool GetDevices() { try { //枚舉所有視頻輸入設備 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videoDevices.Count != 0) { Console.WriteLine("已找到視頻設備."); return true; } return false; } catch (Exception ex) { Console.WriteLine("error:沒有找到視頻設備!具體原因:" + ex.Message); return false; } }
找到控件后就可以初始化攝像頭:
private static void CameraConn() { videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString); vid.VideoSource = videoSource; vid.Start(); }
但是這里為止,都只是攝像拍攝,如果需要拍照,則需要通過eventArgs.Frame.Clone()截取視頻中的某一幀圖像
這里就需要通過事件來處理:
public static void GrabBitmap() { if (videoSource == null) { return; } videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame); //新建事件 } static void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap bmp = (Bitmap)eventArgs.Frame.Clone(); //Clone攝像頭中的一幀 bmp.Save(path, ImageFormat.Png); videoSource.NewFrame -= new NewFrameEventHandler(videoSource_NewFrame); //如果這里不寫這個,一會兒會不停的拍照, }
代碼中的path變量就是圖片保存的位置,讀者們可以自行設置路徑。我這里默認是用戶桌面下的Temp.png文件
測試代碼下載地址:https://gitee.com/GiveCVE/csharp_camera/raw/master/OpenCamera.zip
到此這篇關于C#調用攝像頭實現拍照功能的示例代碼的文章就介紹到這了,更多相關C#調用攝像頭拍照內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#讀取數據庫返回泛型集合詳解(DataSetToList)
本篇文章主要是對C#讀取數據庫返回泛型集合(DataSetToList)進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01