Aforge.net類庫呼叫攝像頭拍照(C#)
阿新 • • 發佈:2019-02-07
官網下載library
新增元件:
先載入列出來所有可用攝像頭放到combobox,從combobox選擇要用的攝像頭
思路:先列出所有攝像頭--開啟攝像頭--抓拍
using System; using System.Drawing; using System.Windows.Forms; using AForge.Video.DirectShow; namespace Aforge { public partial class Form1 : DevComponents.DotNetBar.OfficeForm { public Form1() { InitializeComponent(); } private FilterInfoCollection videoDevices; private VideoCaptureDevice videoSource; private int Indexof = 0; //新增所有的攝像頭到combobox列表裡 private void Camlist() { videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videoDevices.Count == 0) { MessageBox.Show("未找到攝像頭裝置"); } foreach (FilterInfo device in videoDevices) { Cameralist.Items.Add(device.Name); } } //選擇要呼叫的攝像頭,捕獲視訊並展示到videoSourcePlayer1 private void Device_Click(object sender, EventArgs e) { Indexof = Cameralist.SelectedIndex; if (Indexof < 0) { MessageBox.Show("請選擇一個攝像頭"); return; } this.pictureBox1.Visible = false; this.videoSourcePlayer1.Visible = true; //videoDevices[Indexof]確定出用哪個攝像頭了。 videoSource = new VideoCaptureDevice(videoDevices[Indexof].MonikerString); //設定下畫素,這句話不寫也可以正常執行: videoSource.VideoResolution = videoSource.VideoCapabilities[Indexof]; //在videoSourcePlayer1裡顯示 videoSourcePlayer1.VideoSource = videoSource; videoSourcePlayer1.Start(); } //拍照//這裡多了一個pictureBox1,想的是展示下抓拍的照片 private void buttonX1_Click(object sender, EventArgs e) { if (videoSource == null) { MessageBox.Show("請先開啟攝像頭"); return; } //videoSourcePlayer繼承Control父類,定義 GetCurrentVideoFrame能輸出bitmap Bitmap bitmap = videoSourcePlayer1.GetCurrentVideoFrame(); pictureBox1.Image = bitmap; this.videoSourcePlayer1.Visible = false; this.pictureBox1.Visible = true; //這裡停止攝像頭繼續工作 當然videoSourcePlayer裡也定義了 Stop();用哪個都行 videoSourcePlayer1.Stop(); // videoSourcePlayer1.SignalToStop(); videoSourcePlayer1.WaitForStop(); } private void buttonX2_Click(object sender, EventArgs e) { // 加載出來所有的攝像頭 Camlist(); } } }
(新人學習筆記,思路粗劣,讓大家見笑了。)