前言
WPF展示摄像头的方式有很多种比如:OpenCV、EmguCV、Accord、AForge,此片主要讲解AForge。
一、使用 NuGet 搜索 AForge 安装。(如图)
二、在 XAML 中添加 前段代码展示摄像头。
代码如下:
<Grid>
<Image HorizontalAlignment="Stretch" Name="frameHolder" VerticalAlignment="Stretch" Stretch="Fill"/>
</Grid>
三、编写后台逻辑。
代码如下:
VideoCaptureDevice LocalWebCam;
FilterInfoCollection LoaclWebCamsCollection;
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
LoaclWebCamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (LoaclWebCamsCollection.Count <= 0)
{
MessageBox.Show("本机未找到WebCam", "温馨提示");
return;
}
LocalWebCam = new VideoCaptureDevice(LoaclWebCamsCollection[0].MonikerString);
LocalWebCam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
LocalWebCam.Start();
}
private void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
System.Drawing.Image img = (Bitmap)eventArgs.Frame.Clone();
DateTime now = DateTime.Now;
Graphics g = Graphics.FromImage(img);
SolidBrush brush = new SolidBrush(Color.Red);
g.DrawString($"时间:{ now.ToString()}", new System.Drawing.Font("Arial", 18), brush, new PointF(5, 5));
brush.Dispose();
g.Dispose();
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
frameHolder.Source = bi;
}));
}
this.Closed += (s, e) =>
{
if (LocalWebCam == null) return;
LocalWebCam.Stop();
};
效果如下:
blogs: https://www.cnblogs.com/yanjinhua/p/14345136.html
Github:https://github.com/yanjinhuagood
作者:驚鏵
出处:https://www.cnblogs.com/yanjinhua
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
转载请著名作者 出处 https://github.com/yanjinhuagood
技术群:添加小编微信并备注进群
小编微信:mm1552923
公众号:dotNet编程大全