1. 程式人生 > 程式設計 >C#呼叫攝像頭實現拍照功能的示例程式碼

C#呼叫攝像頭實現拍照功能的示例程式碼

前言

老師要求我們學生做一套拍照身份驗證系統,經過長時間的學習,有了這篇文章,希望能幫到讀者們。

正文

首先介紹本文的主角:AForge
建立一個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#呼叫攝像頭拍照內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!