C#调用本机摄像头

2018-06-17 20:49:43来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

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

编写环境:vs2010

语言:C# WPF

 

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

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

 

在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;

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:.NET 内存基础(通过内存体验类型、传参、及装箱拆箱)

下一篇:C#操作Excel(2)-- 打开-读取Excel文档