这段时间一个小项目中需要调用本机的摄像头进行拍照,网上搜集了一些资料以及解决的一些小问题,在此记录以便后续使用。
硬件环境:联想C360一体机,自带摄像头
编写环境:vs2010
语言:C# WPF
下载AForge类库,并添加引用:
usingAForge;usingAForge.Controls;usingAForge.Video;usingAForge.Video.DirectShow;usingSize = System.Drawing.Size;
View Code
在xaml界面中添加VideoSourcePlayer控件,此次稍微解释如何添加外来控件:
在工具箱中添加新的选项卡,右键添加选择项,浏览选择控件dll确定,引用控件即可添加到工具箱中。
枚举所有的摄像头:
FilterInfoCollection videoDevices;
videoDevices=newFilterInfoCollection(FilterCategory.VideoInputDevice);foreach(FilterInfo deviceinvideoDevices)
{//可以做出处理}
连接摄像头:
声明:FileterInfo info;
info = videoDevices[0];//选取第一个,此处可作灵活改动
VideoCaptureDevice videoSource =newVideoCaptureDevice(videoDevices[info.MonikerString);
videoSource.DesiredFrameSize=newSystem.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=newPngBitmapEncoder();
pE.Frames.Add(BitmapFrame.Create(bitmapSource));stringpicName = 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;