C#调用本机摄像头

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

硬件环境:联想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;

 

posted @   小项目笔记  阅读(53021)  评论(2编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

更多文章请关注公众号:小项目笔记

小项目笔记

点击右上角即可分享
微信分享提示