WPF中通过AForge实现USB摄像头拍照

最近由于某种原因呢,需要做一下拍照的功能,本来我纠结到底用AForge类库还是用WPFMediaKit.dll ,不过后来看网上说WPFMediaKit.dll 是截图而AForge是直接通过摄像头拍照,于是乎,我就选择了AForge类库。

首先留下发帖时我所用的AForge    链接:https://pan.baidu.com/s/1htmOjPi 密码:tovd

第一步

  将AForge中的DLL添加进引用,然后添加引用System.Drawing,System.Windows.Forms,WindowsFormsIntegration

第二步

  加上

   xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"

  还有

  <wfi:WindowsFormsHost Grid.Row="0" HorizontalAlignment="Left" Width="517" Height="320" VerticalAlignment="Top">
            <aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/>
        </wfi:WindowsFormsHost>

  下面贴详细代码

MainWindow.xaml

<Window x:Class="FaceOne.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:FaceOne"xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"xmlns:aforge ="clr-namespace:AForge.Controls;assembly=AForge.Controls"mc:Ignorable="d"Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded"><Grid><wfi:WindowsFormsHost Grid.Row="0" HorizontalAlignment="Left" Width="517" Height="320" VerticalAlignment="Top"><aforge:VideoSourcePlayer x:Name="player" Height="480" Width="640"/></wfi:WindowsFormsHost><Button x:Name="connectBtn" Content="连接" HorizontalAlignment="Left" Margin="53,439,0,0" VerticalAlignment="Top" Width="75" Click="connectBtn_Click"/><Button x:Name="captureBtn" Content="拍照" HorizontalAlignment="Left" Margin="180,439,0,0" VerticalAlignment="Top" Width="75" Click="captureBtn_Click"/><Button x:Name="closeBtn" Content="断开" HorizontalAlignment="Left" Margin="312,439,0,0" VerticalAlignment="Top" Width="75" Click="closeBtn_Click"/><Image x:Name="imageCapture" HorizontalAlignment="Left" Height="210" Margin="522,66,0,0" VerticalAlignment="Top" Width="239"/></Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace FaceOne
{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{MyCapture myCapture = MyCapture.Instance();public MainWindow(){InitializeComponent();}private void Window_Loaded(object sender, RoutedEventArgs e){//myCapture.sourcePlayer = player;//配置好XAML后再加上这句,即可看到摄像头的视图
myCapture.getCamera();//获取摄像头myCapture.saveOk += ImageSaveOk;//保存照片后触发
        }//连接private void connectBtn_Click(object sender, RoutedEventArgs e){myCapture.CameraConn();}//拍照private void captureBtn_Click(object sender, RoutedEventArgs e){myCapture.CaputreImage();}//断开private void closeBtn_Click(object sender, RoutedEventArgs e){myCapture.CloseDevice();}//保存照片后触发(想看预览就用,不想看就不需要了)private void ImageSaveOk(string str){/*//老套的赋值方式,不会释放内存BitmapImage bit = new BitmapImage();bit.BeginInit();bit.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory+str);bit.EndInit();imageCapture.Source = bit;*/BitmapImage bmi = myCapture.InitImage(str);imageCapture.Source = bmi;}}
}

MyCapture.cs

using AForge.Controls;
using AForge.Video.DirectShow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;namespace FaceOne
{class MyCapture{public delegate void SaveOk(string str);public SaveOk saveOk;private static MyCapture instance;public static MyCapture Instance(){if (instance == null){instance = new MyCapture();}return instance;}//private static FilterInfoCollection _cameraDevices;private FilterInfoCollection videoDevices;//private static VideoCaptureDevice div = null;
        VideoCaptureDevice videoSource;public VideoSourcePlayer sourcePlayer = new VideoSourcePlayer();public void getCamera(){// 获取电脑已经安装的视频设备videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);if (videoDevices != null && videoDevices.Count > 0){foreach (FilterInfo device in videoDevices){Console.WriteLine(device.Name);}//CameraConn();
            }}//连接并且打开摄像头public void CameraConn(){if (videoDevices.Count <= 0){Console.WriteLine("请插入视频设备");return;}videoSource= new VideoCaptureDevice(videoDevices[0].MonikerString);//连接到第一个设备,可灵活改动//videoSource.DesiredFrameSize = new System.Drawing.Size(240, 320);//videoSource.DesiredFrameRate = 1;
sourcePlayer.VideoSource = videoSource;videoSource.Start();sourcePlayer.Start();}//截取一帧图像并保存public void CaputreImage(string filePath=null,string fileName=null){if (sourcePlayer.VideoSource == null){return;}//判断是否有这个目录,如果没有则新创建这个目录/*if (!Directory.Exists(filePath)){Directory.CreateDirectory(filePath);}*/try{Image bitmap = sourcePlayer.GetCurrentVideoFrame();/*if (fileName == null){fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss");}*///string str = @"" + fileName + ".jpg";string str = "asd.jpg";//使用InitImage可以重复读写一张图,不用的话,就只能一直保存新的图片了bitmap.Save(str,ImageFormat.Jpeg); //想看预览就用,不想看就不需要了
bitmap.Dispose();saveOk(str);}catch(Exception e){Console.WriteLine(e.Message.ToString());}}//关闭摄像头设备public void CloseDevice(){if (videoSource != null && videoSource.IsRunning){sourcePlayer.Stop();videoSource.SignalToStop();videoSource = null;videoDevices = null;}}//解决不同进程读取同一张图片的问题,使用流来读图片public BitmapImage InitImage(string filePath){BitmapImage bitmapImage;using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open))){FileInfo fi = new FileInfo(filePath);byte[] bytes = reader.ReadBytes((int)fi.Length);reader.Close();//image = new Image();bitmapImage = new BitmapImage();bitmapImage.BeginInit();bitmapImage.StreamSource = new MemoryStream(bytes);bitmapImage.EndInit();bitmapImage.CacheOption = BitmapCacheOption.OnLoad;//image.Source = bitmapImage;
                reader.Dispose();}return bitmapImage;}}
}

 

转载于:https://www.cnblogs.com/lingLuoChengMi/p/8466559.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/369595.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php中文字转,PHP文字转图片功能原理与实现方法分析

本文实例讲述了PHP文字转图片功能。分享给大家供大家参考&#xff0c;具体如下&#xff1a;这项功能主要用于对邮箱地址、手机等可能被网络爬虫抓取的重要信息的处理。将文字转化为图片绝对是个好注意。验证码的基本生成原理也与此差不多&#xff0c;只是对再对文字转化为图片的…

Java接口的防御性API演进

API的发展绝对是不平凡的。 只有少数几个需要处理的事情。 我们大多数人每天都在使用内部专有API。 现代IDE附带了很棒的工具&#xff0c;可以分解&#xff0c;重命名&#xff0c;上拉&#xff0c;下推&#xff0c;间接&#xff0c;委托&#xff0c;推断&#xff0c;泛化我们的…

sql语句查询各门课程平均分的最大值

解法一&#xff1a; select courseno,stuno,avg(score) 平均分最高值--这里是求平均&#xff0c;后面的条件是过滤最大值的 from tablename group by courseno,stuno having avg(score) > all (select avg(score) sco--这里是过滤最大值 from tablename group by courseno) …

(转)用JS实现表格中隔行显示不同颜色

用JS实现表格中隔行显示不同颜色 第一种&#xff1a; <style> tr{bgColor:expression( this.bgColor((this.rowIndex)%20 )? white : yellow); } </style> <table id"oTable" width"100" border"1" style"border-colla…

Java 系列之spring学习--spring搭建(一)

一、新建maven项目 二、引入spring jar包 <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0…

php简单分页,php简单实现分页查询的方法

这篇文章主要为大家详细介绍了php简单实现分页查询的方法&#xff0c;具有一定的参考价值&#xff0c;感兴趣的小伙伴们可以参考一下关于php,最近学了好多&#xff0c;老师跟我们说&#xff0c;现在学的都是php的核心部分&#xff0c;所以我比较注意了一下&#xff0c;也多练习…

Java Collections API怪癖

因此&#xff0c;当涉及到Java Collections API时&#xff0c;我们倾向于认为已经了解了所有内容。 我们知道我们的身边方式列表 &#xff0c; 设置 &#xff0c; 地图 &#xff0c; Iterables &#xff0c; 迭代器 。 我们已经为Java 8的Collections API增强做好了准备。 但是…

笔记 — 动画效果(Css3)

/*** animation-name: 调用 keyframes 所定义的动画* animation-duration: 动画周期所花费的时间长度* animation-timing-function: 规定动画的速度曲线* animation-delay: 延时执行动画的时间* animation-iteration-count: 动画执行的次数* animation-dircetion: 规定动画下一…

可命名元组namedtuple

import collectionsMytupleClass collections.namedtuple(MytupleClass,[x,y,z])objMytupleClass(11,22,33)print(obj.x)print(obj.y)print(obj.z)print(dir(obj))print(help(obj))转载于:https://www.cnblogs.com/POP-w/p/7412278.html

django用户认证系统——登录4

用户已经能够在我们的网站注册了&#xff0c;注册就是为了登录&#xff0c;接下来我们为用户提供登录功能。和注册不同的是&#xff0c;Django 已经为我们写好了登录功能的全部代码&#xff0c;我们不必像之前处理注册流程那样费劲了。只需几分钟的简单配置&#xff0c;就可为用…

php缓存类,PHP缓存类

// ----------------------------------------------------------------------// |缓存类// ----------------------------------------------------------------------// | Author: justmepzy(justmepzygmail.com)// -------------------------------------------------------…

双向@OneToMany / @ManyToOne关联

编程的目标之一是代表现实世界中的模型。 通常&#xff0c;应用程序需要对实体之间的某些关系进行建模。 在上一篇有关Hibernate关联的文章中&#xff0c;我描述了建立“一对一”关系的规则。 今天&#xff0c;我将向您展示如何设置双向的“ 一对多 ”和“ 多对一 ”关联。 这个…

web前端黑客技术揭秘 6.漏洞挖掘

6.1  普通XSS漏洞自动化挖掘思路 6.1.1  URL上的玄机 6.1.2  HTML中的玄机 2.HTML标签之内 6.1.3  请求中的玄机 6.1.4  关于存储型XSS挖掘 6.2.1  HTML与JavaScript自解码机制 <input type"button" id"exec_btn" value"exec" on…

Webpack基础使用

目录 一.什么是Webpack 二.为什么要使用Webpack 三.Webpack的使用 1.下载yarn包管理器 2.Webpack的安装 3.Webpack的简单使用 4.效果 四.Webpack打包流程 一.什么是Webpack Webpack是一个静态模块打包工具 二.为什么要使用Webpack 在开发中&#xff0c;我们常常会遇到…

CSS3及JS媒体查询教程

CSS3媒体查询&#xff1a; 语法&#xff1a; <media_query_list>&#xff1a;<media_query>[,<media_query>] <media_query>&#xff1a;only|not <mediaType> and <expression>[ and <expression>] <expression>&#xff1a;…

php mongodb

// 欄位字串為$querys array("name">"shian");// 數值等於多少$querys array("number">7);// 數值大於多少$querys array("number">array($gt > 5));// 數值大於等於多少$querys array("number">array($…

阿帕奇骆驼遇见Redis

键值商店的兰博基尼 Camel是最好的面包集成框架&#xff0c;在本文中&#xff0c;我将向您展示如何通过利用另一个出色的项目Redis使它更加强大。 Camel 2.11即将发布&#xff0c;具有许多新功能&#xff0c;错误修复和组件。 这些新组件中的几个是我创作的&#xff0c; red…

php 数字加逗号,php数字满三位添加一逗号

//数字满三位添加一逗号&#xff1a;$s_money1 1000000;$s_money2 number_format($s_money1);echo $s_money1;//1000000echo "";echo $s_money2;//1,000,000PHP number_format() 函数number_format() 函数通过千位分组来格式化数字。注释&#xff1a;该函数支持一个…

HTML 教程- (HTML5 标准)摘抄笔记

HTML 教程- (HTML5 标准) 教程网址&#xff1a;http://www.runoob.com/html/html-tutorial.html http://blog.csdn.net/ljfbest/article/details/6700148 HTML版本 从初期的网络诞生后&#xff0c;已经出现了许多HTML版本: 版本发布时间HTML1991HTML 1993HTML 2.01995HTML 3…

spring 隔离级别 测试代码

Controller RequestMapping("/test") Api(value "测试", description "测试") public class TestController {Autowiredprivate TestService testService;RequestMapping(value "listForDirtyRead", method RequestMethod.GET)Res…