您的位置:首页 > 编程语言 > C#

C# 启动Windows摄像头类 使用Aforge.net

2017-07-30 17:09 330 查看
/// <summary>
/// 启动摄像头类  需要引用using AForge.Video; using AForge.Video.DirectShow;
/// </summary>
public class Video
{
///---声明变量
private FilterInfoCollection USE_Webcams = null;
private VideoCaptureDevice Camera = null;

public event EventHandler<EventArgs> Realtime_Img_Generation;
public Video()
{
///---实例化对象
USE_Webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice);
///---摄像头数量大于0
if (USE_Webcams.Count > 0)
{

///---实例化对象
Camera = new VideoCaptureDevice(USE_Webcams[0].MonikerString);
///---绑定事件
Camera.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
}
}

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);

private void Cam_NewFrame(object obj, NewFrameEventArgs eventArgs)
{
try
{
System.Windows.Application.Current.Dispatcher.Invoke(new System.Action(() =>
{
var frame = eventArgs.Frame.Clone() as Bitmap;
///---throw new NotImplementedException();
IntPtr ptr = frame.GetHbitmap();
BitmapSource bitmapImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
//release resource
DeleteObject(ptr);
frame.Dispose();
OnRealtime_Img_Generation(eventArgs, bitmapImage);
}));

}
catch (Exception ex)
{
return;
}
}

private void OnRealtime_Img_Generation(EventArgs e, BitmapSource bitMap)
{
EventHandler<EventArgs> handler = Realtime_Img_Generation;

if (handler != null)
handler(bitMap, e);
}

public void StartCamera()
{
Task.Factory.StartNew(() =>
{
if (Camera != null)
{
Camera.Start();
}
});
}

public void StopCamera()
{
Task.Factory.StartNew(() =>
{
if (Camera != null)
{
Camera.Stop();
}
});
}

}


用法示例

private void Window_Loaded(object sender, RoutedEventArgs e)
{
video = new Video();
video.StartCamera();
video.Realtime_Img_Generation += Video_Realtime_Img_Generation;
}

private void Video_Realtime_Img_Generation(object sender, EventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(new System.Action(() =>
{
var bitmap = sender as BitmapSource;
img.Source = bitmap;
}));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: