C#操作Aforge摄像头 实现拍照、录像功能

准备

添加引用
http://download.csdn.net/download/u011463646/10021001
这里写图片描述

.NET 2.0以上 你给项目添加.NET引用 找到PresentationCore添加上就可以了.

这里写图片描述

设计界面

这里写图片描述

运行

这里写图片描述

【代码】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;

//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using Size = System.Drawing.Size;

namespace AforgeCameraOne
{
    public partial class Form1 : Form
    {
        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoSource;
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                foreach (FilterInfo device in videoDevices)
                {
                    int i = 1;
                    tscbxCameras.Items.Add(device.Name);
                    textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");
                    textBoxC.ScrollToCaret();
                    i++;
                }

                tscbxCameras.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                tscbxCameras.Items.Add("No local capture devices");
                videoDevices = null;
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            CameraConn();
        }

        //连接摄像头1
        private void CameraConn()
        {
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer.VideoSource = videoSource;
            videoSourcePlayer.Start();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            videoSourcePlayer.SignalToStop();
            videoSourcePlayer.WaitForStop();
        }
        //主窗体关闭
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            btnClose_Click(null, null);
        }

        private void Photograph_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning)
                {
                    //System.Windows.Media.Imaging
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,//System.Drawing.Imaging;
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + "xiaosy" + ".jpg";
                    textBoxC.AppendText("保存路径:" + picName + "\n");
                    textBoxC.ScrollToCaret();

                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }

        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            //拍照完成后关摄像头并刷新,同时关窗体
            if (videoSourcePlayer != null && videoSourcePlayer.IsRunning)
            {
                videoSourcePlayer.SignalToStop();
                videoSourcePlayer.WaitForStop();
            }

            this.Close();

        }

    }
}

优点

videoSourcePlayer框的大小能够完整显示图像,比AForge Video好多了。

进一步改善,添加连续拍照功能

这里写图片描述

实时保存图像:
这里写图片描述

连续拍照AforgeCameraOne代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;

//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using Size = System.Drawing.Size;

namespace AforgeCameraOne
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegateUI();//多线程问题
        private FilterInfoCollection videoDevices;  //摄像头设备  
        private VideoCaptureDevice videoSource;     //视频的来源选择  
        private VideoSourcePlayer videoSourcePlayer;    //AForge控制控件  
        private VideoFileWriter videoWriter;     //写入到视频  
        private bool is_record_video = false;   //是否开始录像  
        private bool is_multiPhotograph = false; //是否连续拍照 
        System.Timers.Timer timer_count;
        int tick_num = 0;

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                foreach (FilterInfo device in videoDevices)
                {
                    int i = 1;
                    tscbxCameras.Items.Add(device.Name);
                    textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");
                    textBoxC.ScrollToCaret();
                    i++;
                }

                tscbxCameras.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                tscbxCameras.Items.Add("No local capture devices");
                videoDevices = null;
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            CameraConn();
        }

        //连接摄像头1
        private void CameraConn()
        {
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(640, 480);//不起作用
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer.VideoSource = videoSource;
            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
            videoSourcePlayer.Start();
        }

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

        //主窗体关闭
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            btnClose_Click(null, null);
        }

        //拍一次照片
        private void btnPhotograph_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning)
                {
                    //System.Windows.Media.Imaging
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,//System.Drawing.Imaging;
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";
                    textBoxC.AppendText("保存路径:" + picName + "\n");
                    textBoxC.ScrollToCaret();

                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }

        //拍多次照片
        private void btnMultiPhotograph_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim()=="连续拍照")
                {
                    //抓到图保存到指定路径
                    //System.Drawing.Bitmap bmp1 = null;
                    //bmp1 = videoSourcePlayer.GetCurrentVideoFrame();
                    is_multiPhotograph = true;
                    btnMultiPhotograph.Text = "终止拍照";
                    return;//这句重要
                }
                if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim() == "终止拍照")
                {
                    is_multiPhotograph = false;
                    btnMultiPhotograph.Text = "连续拍照";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }

        void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            if (is_multiPhotograph)
            {
                System.Drawing.Bitmap bmp1 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
                string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";
                MyDelegateUI d = delegate
                {
                    this.textBoxC.AppendText("保存路径:" + picName + "\n");
                    textBoxC.ScrollToCaret();
                };
                this.textBoxC.Invoke(d);



                if (File.Exists(picName))
                {
                    File.Delete(picName);
                }
                using (Stream stream = File.Create(picName))
                {
                    bmp1.Save(stream, ImageFormat.Bmp);
                }
            }
        }

        //获得路径
        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }


        //退出按钮
        private void btnExit_Click(object sender, EventArgs e)
        {
            //拍照完成后关摄像头并刷新,同时关窗体
            if (videoSourcePlayer != null && videoSourcePlayer.IsRunning)
            {
                videoSourcePlayer.SignalToStop();
                videoSourcePlayer.WaitForStop();
            }

            this.Close();

        }



    }
}

终极完善,添加Video的录制功能

这次优化了界面初始化的按钮状态,以及随时录制视频的功能。并在Video上打印文字如时间等等。环境配置与AForge Video同。
这里写图片描述
出现问题:
这里写图片描述
拍照+录像代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
using System.Text;
using System.Windows;
using System.Windows.Forms;

//添加的
using System.IO;
using System.Windows.Media.Imaging;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using Size = System.Drawing.Size;

namespace AforgeCameraOne
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegateUI();//多线程问题
        private FilterInfoCollection videoDevices;  //摄像头设备  
        private VideoCaptureDevice videoSource;     //视频的来源选择  
        private VideoSourcePlayer videoSourcePlayer;    //AForge控制控件  
        private VideoFileWriter videoWriter=null;     //写入到视频  
        private bool is_record_video = false;   //是否开始录像  
        private bool is_multiPhotograph = false; //是否连续拍照 
        System.Drawing.Bitmap bmp1 = null;
        System.Timers.Timer timer_count;
        int tick_num = 0;
        int hour = 0;
        int i = 1;           //统计摄像头个数
        int width = 640;    //录制视频的宽度
        int height = 480;   //录制视频的高度
        int fps = 20;        //正常速率,fps越大速率越快,相当于快进

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //初始化按钮状态
            btnClose.Enabled = false;
            btnPhotograph.Enabled = false;
            btnMultiPhotograph.Enabled = false;
            btnStarVideo.Enabled = false;
            btnPuaseVideo.Enabled = false;
            btnStopVideo.Enabled = false;

            try
            {
                // 枚举所有视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

                if (videoDevices.Count == 0)
                    throw new ApplicationException();

                foreach (FilterInfo device in videoDevices)
                {

                    tscbxCameras.Items.Add(device.Name);
                    textBoxC.AppendText("摄像头" + i + "初始化完毕..." + "\n");
                    textBoxC.ScrollToCaret();
                    i++;
                }

                tscbxCameras.SelectedIndex = 0;

            }
            catch (ApplicationException)
            {
                tscbxCameras.Items.Add("No local capture devices");
                videoDevices = null;
            }
            //秒表
            timer_count = new System.Timers.Timer();   //实例化Timer类,设置间隔时间为1000毫秒;
            timer_count.Elapsed += new System.Timers.ElapsedEventHandler(tick_count);   //到达时间的时候执行事件;
            timer_count.AutoReset = true;   //设置是执行一次(false)还是一直执行(true);
            timer_count.Interval = 1000;
        }

        //计时器响应函数
        public void tick_count(object source, System.Timers.ElapsedEventArgs e)
        {
            tick_num++;
            int temp = tick_num;

            int sec = temp % 60;

            int min = temp / 60;
            if (min % 60 == 0)
            {
                hour = min / 60;
                min = 0;
            }
            else
            {
                min = min - hour * 60;
            }
            String tick = hour.ToString() + ":" + min.ToString() + ":" + sec.ToString();
            MyDelegateUI d = delegate
            {
                this.labelTime.Text = tick;
            };
            this.labelTime.Invoke(d);
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            CameraConn();
            //激活初始化按钮状态
            btnClose.Enabled = true;
            btnPhotograph.Enabled = true;
            btnMultiPhotograph.Enabled = true;
            btnStarVideo.Enabled = true;
            btnPuaseVideo.Enabled = true;
            btnStopVideo.Enabled = true;
        }

        //连接摄像头1
        private void CameraConn()
        {
            VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[tscbxCameras.SelectedIndex].MonikerString);
            videoSource.DesiredFrameSize = new System.Drawing.Size(640, 480);//不起作用
            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer.VideoSource = videoSource;
            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
            videoSourcePlayer.Start();
        }

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

        //主窗体关闭
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            btnClose_Click(null, null);
        }

        //拍一次照片
        private void btnPhotograph_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning)
                {
                    //System.Windows.Media.Imaging
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,//System.Drawing.Imaging;
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".jpg";
                    textBoxC.AppendText("保存路径:" + picName + "\n");
                    textBoxC.ScrollToCaret();

                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }

        //拍多次照片
        private void btnMultiPhotograph_Click(object sender, EventArgs e)
        {
            try
            {
                if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim()=="连续拍照")
                {
                    //抓到图保存到指定路径
                    //System.Drawing.Bitmap bmp1 = null;
                    //bmp1 = videoSourcePlayer.GetCurrentVideoFrame();
                    is_multiPhotograph = true;
                    btnMultiPhotograph.Text = "终止拍照";
                    return;//这句重要
                }
                if (videoSourcePlayer.IsRunning && btnMultiPhotograph.Text.Trim() == "终止拍照")
                {
                    is_multiPhotograph = false;
                    btnMultiPhotograph.Text = "连续拍照";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }

        void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            bmp1 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
            //Write Images
            if (is_multiPhotograph)
            {
                string picName = GetImagePath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss-ffff") + ".jpg";
                MyDelegateUI d = delegate
                {
                    this.textBoxC.AppendText("保存路径:" + picName + "\n");
                    textBoxC.ScrollToCaret();
                };
                this.textBoxC.Invoke(d);



                if (File.Exists(picName))
                {
                    File.Delete(picName);
                }
                using (Stream stream = File.Create(picName))
                {
                    bmp1.Save(stream, ImageFormat.Bmp);
                }
            }
            //Write Videos
            if (is_record_video)
            {
                bmp1 = videoSourcePlayer.GetCurrentVideoFrame();
                videoWriter.WriteVideoFrame(bmp1);
            }

        }

        //获得Images路径
        private string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }
        //获取Video相对路径
        private String GetVideoPath()
        {
            String personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString() + "MyVideo";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }

        //退出按钮
        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.videoWriter == null)
            {
                //MessageBox.Show("videoWriter对象未实例化。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
                videoWriter = new VideoFileWriter();
            }
            if (this.videoWriter.IsOpen)
            {
                MessageBox.Show("视频流还没有写完,请点击结束录制。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            //拍照完成后关摄像头并刷新,同时关窗体
            if (videoSourcePlayer != null && videoSourcePlayer.IsRunning)
            {
                videoSourcePlayer.SignalToStop();
                videoSourcePlayer.WaitForStop();
            }

            this.Close();

        }


        //开始录像
        private void btnStarVideo_Click(object sender, EventArgs e)
        {
            try
            {
                //创建一个视频文件
                String picName = GetVideoPath() + "\\" + DateTime.Now.ToString("yyyyMMdd HH-mm-ss") + ".avi";
                textBoxC.AppendText("Video保存地址:" + picName + "\n");
                textBoxC.ScrollToCaret();
                timer_count.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
                textBoxC.AppendText("录制中...\n");
                is_record_video = true;
                videoWriter = new VideoFileWriter();
                if (videoSourcePlayer.IsRunning)
                {
                    videoWriter.Open(picName, width, height, fps, VideoCodec.MPEG4);
                }
                else
                {
                    MessageBox.Show("没有视频源输入,无法录制视频。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("摄像头异常:" + ex.Message);
            }
        }





        //暂停录像
        private void btnPuaseVideo_Click(object sender, EventArgs e)
        {
            if (this.btnPuaseVideo.Text.Trim() == "暂停录像")
            {
                is_record_video = false;
                this.btnPuaseVideo.Text = "恢复录像";
                timer_count.Enabled = false;    //暂停计时
                return;
            }
            if (this.btnPuaseVideo.Text.Trim() == "恢复录像")
            {
                is_record_video = true;
                this.btnPuaseVideo.Text = "暂停录像";
                timer_count.Enabled = true;     //恢复计时
            }
        }

        private void btnStopVideo_Click(object sender, EventArgs e)
        {
            this.is_record_video = false;
            this.videoWriter.Close();
            this.timer_count.Enabled = false;
            tick_num = 0;
            textBoxC.AppendText("录制停止!\n");
            textBoxC.ScrollToCaret();
        }


    }
}

参考

【1】C#操作摄像头 实现拍照功能 - 迷失的醉猫 - 博客园
http://www.cnblogs.com/xsyblogs/p/3551986.html
【2】C# 调用AForge类库操作摄像头 - CSDN博客
http://blog.csdn.net/chenhongwu666/article/details/40594365

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何以问天涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值