C# WPF使用AForge类库操作USB摄像头拍照并保存

2020-01-05 09:39:41王冬梅

对 CameraHelper.cs 中的 CaptureImage 函数做一点修改:


/// <summary>
/// 截取一帧图像并保存
/// </summary>
/// <param name="filePath">图像保存路径</param>
/// <param name="fileName">保存的图像文件名</param>
/// <returns>如果保存成功,则返回完整路径,否则为 null</returns>
 public static string CaptureImage(string filePath, string fileName = null)
  {
   if (sourcePlayer.VideoSource == null) return null;
   if (!Directory.Exists(filePath))
   {
    Directory.CreateDirectory(filePath);
   }
   try
   {
    Image bitmap = sourcePlayer.GetCurrentVideoFrame();
    if(fileName == null) fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
    string fullPath = Path.Combine(filePath, fileName + "-cap.jpg");
    bitmap.Save(fullPath, ImageFormat.Jpeg);
    bitmap.Dispose();
    return fullPath;
   }
   catch (Exception e)
   {
    MessageBox.Show(e.Message.ToString());
    return null;
   }
}

修改后台代码如下:


using System;
using System.Windows;
using System.Windows.Media.Imaging;

namespace AForgeTest
{
 /// <summary>
 /// MainWindow.xaml 的交互逻辑
 /// </summary>
 public partial class MainWindow : Window
 {
  public MainWindow()
  {
   InitializeComponent();
   CameraHelper.IsDisplay = true;
   CameraHelper.SourcePlayer = player;
   CameraHelper.UpdateCameraDevices();
  }

  private void btnOpenCamera_Click(object sender, EventArgs e)
  {
   if (CameraHelper.CameraDevices.Count > 0)
   {
    CameraHelper.SetCameraDevice(0);
   }
  }

  private void btnCapture_Click(object sender, EventArgs e)
  {
   string fullPath = CameraHelper.CaptureImage(AppDomain.CurrentDomain.BaseDirectory + @"Capture");

   BitmapImage bit = new BitmapImage();
   bit.BeginInit();
   bit.UriSource = new Uri(fullPath);
   bit.EndInit();
   imgCapture.Source = bit;
  }

  private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
   CameraHelper.CloseDevice();
  }
 }
}

最终结果如下:

C#,WPF,AForge,类库,USB,摄像头,拍照