关于.net下的摄像头操作,一般选用Aforge.net 框架的几个dll文件,功能强大,操作简单,不过在实际操作中坑中的不少,下面我就来演示常用的操作。

Aforge.net 官网:http://www.aforgenet.com/aforge/framework/

关于Aforge.net的简介:=>简介<=

一,下载完后,解压,引用下列文件

AForge.dll 是根文件

Aforge.Controls是控件集

AForge.Video及AForge.Video.DirectShow 是操作视频的核心文件

二,引用命名空间:

using AForge;
using AForge.Video;
using AForge.Video.DirectShow;

三,添加控件

如图,点击浏览选项后选中我们引用的AForge.Controls.dll 文件,这样会导入如下控件;

插入我们的WinForm中

在后台写入如下代码;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge;
using AForge.Video;
using AForge.Video.DirectShow;


namespace DemoCamera
{
  public partial class FrmMain : Form
  {

      private FilterInfoCollection videoDevices;
      private VideoCaptureDevice videoSource;

      private bool Record;
      private PictureBox piccapture;

      public FrmMain()
      {

          InitializeComponent();
          InitForm();
      }


      private void InitForm()
      {
          videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
          foreach (FilterInfo item in videoDevices)
          {
              cbxcamera.Items.Add(item.Name);
          }
          this.ClientSize = Screen.PrimaryScreen.Bounds.Size;
          vfplayer.Height = this.Height - 100;

          piccapture = new PictureBox();
          piccapture.Site = this.Site;
          piccapture.Dock = DockStyle.Fill;
          piccapture.SendToBack();
          piccapture.Visible = false;
          this.Controls.Add(piccapture);

      }

      private void btnstart_Click(object sender, EventArgs e)
      {
          videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
          if (videoSource != null)
          {
              vfplayer.VideoSource = videoSource;
              vfplayer.NewFrame += vfplayer_NewFrame;
              vfplayer.BackgroundImageLayout = ImageLayout.Zoom;
              vfplayer.Start();
          }

      }


      void vfplayer_NewFrame(object sender, ref Bitmap image)
      {
          if (Record)
          {
              //videowriter.Open("1.mp4", image.Width, image.Height, 20, VideoCodec.MPEG4);
              //videowriter.WriteVideoFrame(image);
          }
      }

      private void btnrecord_Click(object sender, EventArgs e)
      {
          Record = true;
      }

      private void btnstop_Click(object sender, EventArgs e)
      {
          Record = false;
          vfplayer.Stop();
      }

      private void btncapture_Click(object sender, EventArgs e)
      {
          if (vfplayer.IsRunning)
          {
              piccapture.Image = vfplayer.GetCurrentVideoFrame();
              piccapture.Show();
              vfplayer.Visible = false;
          }
      }


  }
}

三步搞定摄像头打开,拍照功能,效果图如下;