zoukankan      html  css  js  c++  java
  • C#调用本机摄像头

    这段时间一个小项目中需要调用本机的摄像头进行拍照,网上搜集了一些资料以及解决的一些小问题,在此记录以便后续使用。

    硬件环境:联想C360一体机,自带摄像头

    编写环境:vs2010

    语言:C# WPF

    下载AForge类库,并添加引用:

    using AForge;
    using AForge.Controls;
    using AForge.Video;
    using AForge.Video.DirectShow;
    using Size = System.Drawing.Size;

    在xaml界面中添加VideoSourcePlayer控件,此次稍微解释如何添加外来控件:

    在工具箱中添加新的选项卡,右键添加选择项,浏览选择控件dll确定,引用控件即可添加到工具箱中。

    枚举所有的摄像头:

    复制代码
    FilterInfoCollection videoDevices;
    videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    
    foreach (FilterInfo device in videoDevices)
                    {
                        //可以做出处理
                    }
    复制代码

    连接摄像头:

    复制代码
    声明:FileterInfo info;
    info = videoDevices[0];//选取第一个,此处可作灵活改动

    VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[info.MonikerString); videoSource.DesiredFrameSize = new System.Drawing.Size(214, 281); videoSource.DesiredFrameRate = 1; videoSourcePlayer.VideoSource = videoSource; videoSourcePlayer.Start();
    复制代码

    关闭摄像头:

    videoSourcePlayer.SignalToStop();
                videoSourcePlayer.WaitForStop();

    拍照:

    复制代码
    if (videoSourcePlayer.IsRunning)
                    {
                string path = "e:" BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( videoSourcePlayer.GetCurrentVideoFrame().GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); PngBitmapEncoder pE = new PngBitmapEncoder(); pE.Frames.Add(BitmapFrame.Create(bitmapSource)); string picName = path + "paizhao" + ".jpg"; if (File.Exists(picName)) { File.Delete(picName); } using (Stream stream = File.Create(picName)) { pE.Save(stream); } }
    复制代码

    项目中要求是摄像头处于监控状态,拍照后画面固定存储,不满意可以清空再次进行拍照,直到满意为止。

    做法是在videoSourcePlayer的上面添加一个image控件,因为项目是WPF做的,所有照片显示只能添加image控件,有两点需要注意:

    1)WPF引用winform控件需要使用WindowsFormsHost控件,所以监控视频和照片显示时是控件WindowsFormsHost和image控件的显示和隐藏,此处走了一段弯路所以记录下来。

    2)image控件的source已经绑定,但是照片需要清空删除该照片资源,系统提示的大致意思是资源已经被占用无法删除。解决途径:

    声明:BitmapImage bmi = new System.Windows.Media.Imaging.BitmapImage();

    使用时:bmi.BgeinInit();

    bmi.UriSource = new Uri(picName);

    bmi.CacheOption = BitmapCacheOption.OnLoad;

    bmi.EndInit();

    绑定:this.image.Source = bmi;

  • 相关阅读:
    windows系统切换jdk,修改java_home无效情况
    Cannot instantiate interface org.springframework.context.ApplicationListener
    MySQL分组查询获取每个学生前n条分数记录(分组查询前n条记录)
    ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET
    EF TO MYSQL 无法查询中文的解决方法
    HttpWebRequest post请求获取webservice void数据信息
    This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分 解决方案
    MySQL 5.7.13解压版安装记录 mysql无法启动教程
    C# udpclient 发送数据断网后自动连接的方法
    汽车XX网站秒杀抢购代码
  • 原文地址:https://www.cnblogs.com/weihengblogs/p/4964792.html
Copyright © 2011-2022 走看看