Win10 UWP开发:摄像头扫描二维码/一维码功能
这个示例演示整合了Aran和微软的示例,无需修改即可运行。
支持识别,二维码/一维码,需要在包清单管理器勾选摄像头权限。
首先右键项目引用,打开Nuget包管理器搜索安装:ZXing.Net.Mobile
BarcodePage.xmal页面代码
<Pagex:Class="SuperTools.Views.BarcodePage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="using:SuperTools.Views"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"><Page.Transitions><TransitionCollection><NavigationThemeTransition><SlideNavigationTransitionInfo /></NavigationThemeTransition></TransitionCollection></Page.Transitions><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"><Grid x:Name="LayoutRoot" ><Grid x:Name="ContentPanel" ><!--视频流预览--><CaptureElement x:Name="VideoCapture" Stretch="UniformToFill"/><Grid Width="300" Height="300" x:Name="ViewGrid"><Rectangle Width="3" Height="50" Fill="Orange" HorizontalAlignment="Left" VerticalAlignment="Top"/><Rectangle Width="3" Height="50" Fill="Orange" HorizontalAlignment="Right" VerticalAlignment="Top"/><Rectangle Width="3" Height="50" Fill="Orange" HorizontalAlignment="Left" VerticalAlignment="Bottom"/><Rectangle Width="3" Height="50" Fill="Orange" HorizontalAlignment="Right" VerticalAlignment="Bottom"/><Rectangle Width="50" Height="3" Fill="Orange" HorizontalAlignment="Left" VerticalAlignment="Top"/><Rectangle Width="50" Height="3" Fill="Orange" HorizontalAlignment="Right" VerticalAlignment="Top"/><Rectangle Width="50" Height="3" Fill="Orange" HorizontalAlignment="Left" VerticalAlignment="Bottom"/><Rectangle Width="50" Height="3" Fill="Orange" HorizontalAlignment="Right" VerticalAlignment="Bottom"/><Rectangle x:Name="recScanning" Margin="12,0,12,0" VerticalAlignment="Center" Height="2" Fill="Green" RenderTransformOrigin="0.5,0.5" /></Grid></Grid></Grid></Grid> </Page>
BarcodePage.xmal.cs后台代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Graphics.Display; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Media.Capture; using Windows.Media.Devices; using Windows.Media.MediaProperties; using Windows.Storage; using Windows.Storage.FileProperties; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using ZXing;// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板namespace SuperTools.Views {/// <summary>/// 可用于自身或导航至 Frame 内部的空白页。/// </summary>public sealed partial class BarcodePage : Page{private Result _result;private MediaCapture _mediaCapture;private DispatcherTimer _timer;private bool IsBusy;private bool _isPreviewing = false;private bool _isInitVideo = false;BarcodeReader barcodeReader;private static readonly Guid RotationKey = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1");public BarcodePage(){barcodeReader = new BarcodeReader{AutoRotate = true,Options = new ZXing.Common.DecodingOptions { TryHarder = true }};this.InitializeComponent();this.NavigationCacheMode = NavigationCacheMode.Required;Application.Current.Suspending += Application_Suspending;Application.Current.Resuming += Application_Resuming;}private async void Application_Suspending(object sender, SuspendingEventArgs e){// Handle global application events only if this page is activeif (Frame.CurrentSourcePageType == typeof(MainPage)){var deferral = e.SuspendingOperation.GetDeferral();await CleanupCameraAsync();deferral.Complete();}}private void Application_Resuming(object sender, object o){// Handle global application events only if this page is activeif (Frame.CurrentSourcePageType == typeof(MainPage)){InitVideoCapture();}}protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e){// Handling of this event is included for completenes, as it will only fire when navigating between pages and this sample only includes one pageawait CleanupCameraAsync();}protected override void OnNavigatedTo(NavigationEventArgs e){base.OnNavigatedTo(e);InitVideoCapture();}private async Task CleanupCameraAsync(){if (_isPreviewing){await StopPreviewAsync();}_timer.Stop();if (_mediaCapture != null){_mediaCapture.Dispose();_mediaCapture = null;}}private void InitVideoTimer(){_timer = new DispatcherTimer();_timer.Interval = TimeSpan.FromSeconds(1);_timer.Tick += _timer_Tick;_timer.Start();}private async Task StopPreviewAsync(){_isPreviewing = false;await _mediaCapture.StopPreviewAsync();// Use the dispatcher because this method is sometimes called from non-UI threadsawait Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>{VideoCapture.Source = null;});}private async void _timer_Tick(object sender, object e){try{if (!IsBusy){IsBusy = true;var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;VideoFrame videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);VideoFrame previewFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame);WriteableBitmap bitmap = new WriteableBitmap(previewFrame.SoftwareBitmap.PixelWidth, previewFrame.SoftwareBitmap.PixelHeight);previewFrame.SoftwareBitmap.CopyToBuffer(bitmap.PixelBuffer);await Task.Factory.StartNew(async () => { await ScanBitmap(bitmap); });}IsBusy = false;await Task.Delay(50);}catch (Exception){IsBusy = false;}}/// <summary>/// 解析二维码图片/// </summary>/// <param name="writeableBmp">图片</param>/// <returns></returns>private async Task ScanBitmap(WriteableBitmap writeableBmp){try{await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>{_result = barcodeReader.Decode(writeableBmp.PixelBuffer.ToArray(), writeableBmp.PixelWidth, writeableBmp.PixelHeight, RGBLuminanceSource.BitmapFormat.Unknown);if (_result != null){//TODO: 扫描结果:_result.Text }});}catch (Exception){}}private async void InitVideoCapture(){///摄像头的检测 var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);if (cameraDevice == null){System.Diagnostics.Debug.WriteLine("No camera device found!");return;}var settings = new MediaCaptureInitializationSettings{StreamingCaptureMode = StreamingCaptureMode.Video,MediaCategory = MediaCategory.Other,AudioProcessing = AudioProcessing.Default,VideoDeviceId = cameraDevice.Id};_mediaCapture = new MediaCapture();await _mediaCapture.InitializeAsync(settings);VideoCapture.Source = _mediaCapture;await _mediaCapture.StartPreviewAsync();var props = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);props.Properties.Add(RotationKey, 90);await _mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, props, null);var focusControl = _mediaCapture.VideoDeviceController.FocusControl;if (focusControl.Supported){await focusControl.UnlockAsync();var setting = new FocusSettings { Mode = FocusMode.Continuous, AutoFocusRange = AutoFocusRange.FullRange };focusControl.Configure(setting);await focusControl.FocusAsync();}_isPreviewing = true;_isInitVideo = true;InitVideoTimer();}private static async Task<DeviceInformation> FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel desiredPanel){var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);DeviceInformation desiredDevice = allVideoDevices.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredPanel);return desiredDevice ?? allVideoDevices.FirstOrDefault();}} }
转载于:https://www.cnblogs.com/myhalo/p/6635325.html
Win10 UWP开发:摄像头扫描二维码/一维码功能相关推荐
- h5端呼起摄像头扫描二维码并解析
2016年6月29日补充: 最近做了一些与表单相关的项目,使用了h5的input控件,在使用过程中遇到了很多的坑.也包括与这篇文章相关的. 首先我们应该知道使用h5新提供的属性getUserMedia ...
- SLAM无人车通过上摄像头扫描二维码重定位
SLAM无人车通过上摄像头扫描二维码重定位 slam 无人车扫描二维码重定位initpose 实现原理: 1.内参标定 2.外参标定得到相机相对于小车的安装坐标 3.通过功能包 ar_track_al ...
- PC端调用摄像头扫描二维码,拿到二维码信息
PC端调用摄像头扫描二维码,拿到二维码信息 <template><el-dialogtitle="扫描设备二维码":visible.sync="dial ...
- Python实现PC摄像头扫描二维码,让你的电脑变身QR码识读器!
目录 简介: 源代码: 源代码说明: 效果如下所示: 简介: 使用PC摄像机扫描二维码可以有很多应用场景,例如: 支付宝.微信支付等移动支付方式需要使用二维码进行支付,PC摄像机可以扫描这些支付二维码 ...
- C#生成二维码、调用摄像头扫描二维码
二维码的生成和解码,有两个开源项目可以参考: 一个是google的zxing,另外一个是ThroughWork. zxing做的很全面,支持各种语言和平台,具体不多讲,自己查去.ThroughWork ...
- IOS抖音短视频APP开发关于扫描二维码,并根据文本生成二维码
IOS抖音短视频APP开发关于扫描二维码,(根据光线强弱显示隐藏闪光灯)并根据文本生成二维码. WeakSelf; //IOS抖音短视频APP开发构建扫描样式视图 _scanView = [[WSLS ...
- 关于Unity调用摄像头扫描二维码与生成二维码的实现方法
1.常用的生成二维码网址 https://cli.im/ 2.上官网下载二维码插件 http://zxingnet.codeplex.com/ 3.将下载的插件中zxing.unity.dll文件放入 ...
- 能在Windows CE上运行的的二维码识别系统,使用手机摄像头扫描二维码
欧美和日本,二维码的使用比较广泛,最近看到一则新闻,我们国家也在航空服务中使用二维码了.二维码具有信息容量大.纠错能力强.可靠性高.成本低.防伪性好.持久耐用等一维条码所不具备的优良特点.二维码的种类 ...
- vue实现调用摄像头扫描二维码
安装依赖:vue-qrcode-reader npm install vue-qrcode-reader -s 直接上代码 <template><div><div cla ...
最新文章
- golang 系统调用 syscall 简介
- JS 活学活用正则表达式
- 距离剩者为王,服饰企业还要跨过很多道坎
- 一、“用黑色的眼睛寻找光明”
- 如何使得WIN7下用VS2010做出的MFC程序具有XP风格(摆脱传统界面的效果)
- [转] 深入浅出 妙用Javascript中apply、call、bind
- Time-of-Flight技术在距离测量和定位上的应用
- msgpack java lua_使用lua-cmsgpack序列化和反序列化lua对象
- [LeetCode]--35. Search Insert Position
- struts2文件下载及文件名中文问题
- java response 输出word_java导出数据到word(一)
- Google的C++编程规范总结
- 微型计算机中backspace键是什么键,backspace是哪个键?最实用按键的大揭秘
- e4a java_易安卓e4a编译生成R.java文件失败的解决办法
- 关于家里的宽带和无线wifi路由器的一些选择和配置
- C++——百分制成绩转五分制成绩
- MySQL大表DDL工具gh-ost
- 北京哪些医院不用特意选择就可用社保卡直接就医?
- 【PostgreSQL】PostgreSQL的upsert功能(insert on conflict do)的用法
- 网线连接olt配置计算机IP,EPON-ONU-OLT配置手册.pdf
热门文章
- CYQ.Data V5 从入门到放弃ORM系列:教程 - MAction类使用
- Ubuntu 中Eclipse 默认的OpenJDK 和 SUNJDK问题总结
- 【转】 SED多行模式空间
- 数学之美 系列十六 (下)- 不要把所有的鸡蛋放在一个篮子里 最大熵模型...
- ubuntu squid 做http代理
- Android编译笔记二
- sysfs API总结
- 汉诺塔算法python_经典算法:汉诺塔
- bat判断文件是否存在_BAT面试必问题系列:JVM判断对象是否已死和四种垃圾回收算法总结...
- win10专业版虚拟机配置服务器,虚拟机专用专业版win10 账号密码