欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# WPF使用AForge類庫操作USB攝像頭拍照并保存

 更新時間:2022年03月27日 08:20:57   作者:曉風-楊柳  
這篇文章主要為大家詳細介紹了C# WPF使用AForge類庫操作USB攝像頭拍照并保存,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

項目中用到 USB 攝像頭,需要根據情況進行圖像抓拍,查了半天資料,比較多的是使用 WPFMediaKit 和 AForge 。
但是由于項目要求不顯示 USB 攝像頭拍攝的畫面,最終確定使用 AForge 解決。
下面用一個測試程序記錄一下。

一、無預覽拍照

首先建立一個 WPF 項目,我的就叫 AForgeTest,你們隨意就好:

然后在 NuGet 包管理器中安裝 AForge 庫:

我只安裝了圖中打勾的幾個庫,這個根據自己項目需要安裝就好。
不過用 USB 攝像頭拍照必須安裝:
AForge.Video
AForge.Control
AForge.Video.DirectShow
這三個庫文件。

不習慣使用 NuGet 也可以到 AForge 的 .NET lib 下載頁面下載。

在 MainWindow.xaml 文件中添加兩個按鈕:

<Window x:Class="AForgeTest.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:local="clr-namespace:AForgeTest"
  mc:Ignorable="d"
  Title="MainWindow" Height="300" Width="300"
  Closing="Window_Closing">
 <StackPanel>
  <Button Name="btnCapture" Click="btnCapture_Click">拍照</Button>
  <Button Name="btnOpenCamera" Click="btnOpenCamera_Click">打開</Button>
 </StackPanel>
</Window>

后臺交互邏輯如下:

using System;
using System.Windows;

namespace AForgeTest
{
 /// <summary>
 /// MainWindow.xaml 的交互邏輯
 /// </summary>
 public partial class MainWindow : Window
 {
  public MainWindow()
  {
   InitializeComponent();
  }

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

  private void btnCapture_Click(object sender, EventArgs e)
  {
   CameraHelper.CaptureImage(@"E:\1");
  }

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

CameraHelper 類代碼如下:

using System;
using AForge.Video.DirectShow;
using AForge.Controls;
using System.Windows;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace AForgeTest
{
 public static class CameraHelper
 {
  private static FilterInfoCollection _cameraDevices;
  private static VideoCaptureDevice div = null;
  private static VideoSourcePlayer sourcePlayer = new VideoSourcePlayer();
  private static bool _isDisplay = false;
  //指示_isDisplay設置為true后,是否設置了其他的sourcePlayer,若未設置則_isDisplay重設為false
  private static bool isSet = false;

  /// <summary>
  /// 獲取或設置攝像頭設備,無設備為null
  /// </summary>
  public static FilterInfoCollection CameraDevices
  {
   get
   {
    return _cameraDevices;
   }
   set
   {
    _cameraDevices = value;
   }
  }
  /// <summary>
  /// 指示是否顯示攝像頭視頻畫面
  /// 默認false
  /// </summary>
  public static bool IsDisplay
  {
   get { return _isDisplay; }
   set { _isDisplay = value; }
  }
  /// <summary>
  /// 獲取或設置VideoSourcePlayer控件,
  /// 只有當IsDisplay設置為true時,該屬性才可以設置成功
  /// </summary>
  public static VideoSourcePlayer SourcePlayer
  {
   get { return sourcePlayer; }
   set
   {
    if (_isDisplay)
    {
     sourcePlayer = value;
     isSet = true;
    }

   }
  }
  /// <summary>
  /// 更新攝像頭設備信息
  /// </summary>
  public static void UpdateCameraDevices()
  {
   _cameraDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
  }
  /// <summary>
  /// 設置使用的攝像頭設備
  /// </summary>
  /// <param name="index">設備在CameraDevices中的索引</param>
  /// <returns><see cref="bool"/></returns>
  public static bool SetCameraDevice(int index)
  {
   if (!isSet) _isDisplay = false;
   //無設備,返回false
   if (_cameraDevices.Count <= 0 || index < 0) return false;
   if (index > _cameraDevices.Count - 1) return false;
   // 設定初始視頻設備
   div = new VideoCaptureDevice(_cameraDevices[index].MonikerString);
   sourcePlayer.VideoSource = div;
   div.Start();
   sourcePlayer.Start();
   return true;
  }
  /// <summary>
  /// 截取一幀圖像并保存
  /// </summary>
  /// <param name="filePath">圖像保存路徑</param>
  /// <param name="fileName">保存的圖像文件名</param>
  public static void CaptureImage(string filePath, string fileName = null)
  {
   if (sourcePlayer.VideoSource == null) return;
   if (!Directory.Exists(filePath))
   {
    Directory.CreateDirectory(filePath);
   }
   try
   {
    //sourcePlayer.Start();
    Image bitmap = sourcePlayer.GetCurrentVideoFrame();
    if(fileName == null) fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");
    bitmap.Save(filePath + @"\" + fileName + "-cap.jpg", ImageFormat.Jpeg);
    bitmap.Dispose();
    //sourcePlayer.Stop();
   }
   catch (Exception e)
   {
    MessageBox.Show(e.Message.ToString());
   }
  }
  /// <summary>
  /// 關閉攝像頭設備
  /// </summary>
  public static void CloseDevice()
  {
   if (div != null && div.IsRunning)
   {
    sourcePlayer.Stop();
    div.SignalToStop();
    div = null;
    _cameraDevices = null;
   }
  }
 }
}

最終效果如下:

首先單擊打開按鈕,然后單擊拍照按鈕,就會在指定路徑下生成一個 jpg 文件。

單擊打開按鈕之后需要等待 2s 以上才能點擊拍照(需要等待連接到攝像頭),否則會報出異常,如下圖:

二、顯示攝像頭拍攝畫面和截取的圖片

首先添加 System.Windows.Forms 和 WindowsFormsIntegration 的引用。
然后在 MainWindows.xmal 文件中加命名空間:

xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"12

添加 VideoSourcePlayer 和 Image 控件:

<wfi:WindowsFormsHost Grid.Row="0">
 <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/>
</wfi:WindowsFormsHost>
<Image Grid.Row="0" Grid.Column="1" Name="imgCapture" Stretch="Fill" Height="480" Width="640"/>

這里有個小細節(jié),注意對 VideoSourcePlayer 命名時,一定要使用 x:Name 不要省略 x: ,否則無法在后臺代碼中使用(不要問我是怎么知道的)。

對 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#文本加密程序代碼示例

    c#文本加密程序代碼示例

    這是一個加密軟件,但只限于文本加密,加了窗口控件的滑動效果,詳細看下面的代碼
    2013-11-11
  • C#實現自定義ListBox背景的示例詳解

    C#實現自定義ListBox背景的示例詳解

    這篇文章主要為大家詳細介紹了如何利用C#實現自定義ListBox背景,文中的示例代碼講解詳細,對我們學習C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下
    2022-12-12
  • C# 基礎入門--常量

    C# 基礎入門--常量

    本文主要介紹了C#中常量的相關知識,具有很好的參考價值。下面跟著小編一起來看下吧
    2017-03-03
  • C#操作txt文件,進行清空添加操作的小例子

    C#操作txt文件,進行清空添加操作的小例子

    這篇文章介紹了C#操作txt文件,進行清空添加操作的小例子,有需要的朋友可以參考一下
    2013-09-09
  • C# 使用modbus 讀取PLC 寄存器地址的方法

    C# 使用modbus 讀取PLC 寄存器地址的方法

    今天通過本文給大家介紹C# 使用modbus 讀取PLC 寄存器地址的方法,使用的組件Nmodbus,文中通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧
    2021-10-10
  • C#實現基于XML配置MenuStrip菜單的方法

    C#實現基于XML配置MenuStrip菜單的方法

    這篇文章主要介紹了C#實現基于XML配置MenuStrip菜單的方法,涉及C#使用XML配置MenuStrip菜單的原理與實現技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-08-08
  • C#單例模式(Singleton Pattern)實例教程

    C#單例模式(Singleton Pattern)實例教程

    這篇文章主要介紹了C#單例模式(Singleton Pattern)的實現方法,主要講述了即時加載的單例模式、延遲加載的單例模式與線程安全的單例模式,需要的朋友可以參考下
    2014-09-09
  • C# Quartzs定時器的使用教程

    C# Quartzs定時器的使用教程

    想到倒計時,定時任務,大家首先想到的肯定就是定時器,定時器在web和winfrom程序中也有著很大的作用。本文也將為大家介紹Quartzs定時器的簡單使用。需要的朋友可以參考一下
    2021-11-11
  • c# 使用模式匹配以及 is 和 as 運算符安全地進行強制轉換

    c# 使用模式匹配以及 is 和 as 運算符安全地進行強制轉換

    這篇文章主要介紹了c# 使用模式匹配以及 is 和 as 運算符安全地進行強制轉換,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-10-10
  • C#實現一階卡爾曼濾波算法的示例代碼

    C#實現一階卡爾曼濾波算法的示例代碼

    這篇文章主要介紹了C#實現一階卡爾曼濾波算法的示例代碼,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下
    2021-04-04

最新評論