不少都是C#調用window API 發送SendMessage,實現操做攝像頭,可是C#調用window API的時候由於驅動的問題,老是彈出視頻選擇對話框,讓人非常無語,看到大牛們有的截獲到了window消息,而後模擬點擊肯定按鈕,這是在是不敢恭維啊,還有的大牛根據API原型重寫了,至於我是一隻IT小小鳥了,而後在繼續百度,找到了一個AForge強大的C#類庫,最後終於搞定了,接下來將我拙劣的代碼部分貼出來,以便同行或者須要的朋友學習交流,ide
首先用到AForge類庫下載地址:http://www.aforgenet.com/工具
而後引用AForge,AForge.Controls(這個是控件,能夠添加到工具箱中),AForge.Imaging,AForge.Video,AForge.Video.DirectShow;學習
而後直接上代碼.net
private FilterInfoCollection videoDevices;
private VideoCaptureDevice videoSource;
public int selectedDeviceIndex = 0;視頻
下面是獲取設備blog
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;
}
}原型
選擇設備,而後鏈接攝像頭string
<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)
return null;
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);
}it
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);
}io
這樣就完成了操做攝像頭的工做
可是發現一個問題,若是要拍照獲得的照片先要處理在保存,這裏就有問題了,因此須要在界面前臺中添加控件,醫用AForge.Controls,而後添加到工具箱,而後將VideoSourcePlayer控件拖到窗體中,想要獲得單張圖像處理:
Bitmap bmp = videoSourcePlayer1.GetCurrentFrame();