萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 使用 AForge.NET 實現攝像頭拍照、預覽與錄影

專案架構

  • WinForms 專案,引用 AForge.Video.DirectShow、AForge.Controls、AForge.Video.FFMPEG(錄影需)。
  • 工具箱拖入 VideoSourcePlayer(來自 AForge.Controls)作為預覽畫面。
主介面
參考 DLL 清單

核心代碼

1. 列舉裝置並綁定 ComboBox

private FilterInfoCollection videoDevices;

private void Form1_Load(object sender, EventArgs e) {
    try {
        videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        if (videoDevices.Count == 0) throw new ApplicationException();
        foreach (FilterInfo dev in videoDevices)
            tscbxCameras.Items.Add(dev.Name);
        tscbxCameras.SelectedIndex = 0;
    } catch {
        tscbxCameras.Items.Add("No local capture devices");
        videoDevices = null;
    }
}

2. 連線/預覽

private void CameraConn() {
    var videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
    videoSource.DesiredFrameSize = new Size(320, 240);
    videoSource.DesiredFrameRate = 15;
    videoSourcePlayer.VideoSource = videoSource;
    videoSourcePlayer.Start();
}

3. 關閉裝置

private void btnClose_Click(object sender, EventArgs e) {
    videoSourcePlayer.SignalToStop();
    videoSourcePlayer.WaitForStop();
}

4. 拍照存檔(PNG)

private void Photograph_Click(object sender, EventArgs e) {
    try {
        if (videoSourcePlayer.IsRunning) {
            var bitmap = videoSourcePlayer.GetCurrentVideoFrame();
            string path = GetImagePath() + "\\xiaosy.jpg";
            if (File.Exists(path)) File.Delete(path);
            bitmap.Save(path, ImageFormat.Jpeg); // 直接用 GDI+ 儲存

            // 關閉裝置並關閉視窗
            videoSourcePlayer.SignalToStop();
            videoSourcePlayer.WaitForStop();
            this.Close();
        }
    } catch (Exception ex) {
        MessageBox.Show("攝像頭異常:" + ex.Message);
    }
}

private string GetImagePath() {
    string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PersonImg");
    if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
    return dir;
}

錄影擴充提示

引用 AForge.Video.FFMPEG,使用 VideoFileWriter 在 `NewFrame` 事件中寫入幀,停止時呼叫 `Close()`。下一篇將補充完整錄影範例。

copyright © 萬盛學電腦網 all rights reserved