您的位置:首页 > 教程文章 > 编程开发

C#实现调用本机录像实例

:0 :2021-04-22 22:14:03

本文实例源自一个项目,其中需要调用本机的录像进行拍照,分享给大家供大家参考之用。具体步骤如下:
硬件环境:联想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;
希望本文所述对于大家的C#程序设计有所帮助。

WinForm中DefWndProc、WndProc与IMessageFilter的区别
C#之Socket操作类实例解析

同类资源