博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Win10 UWP开发:摄像头扫描二维码/一维码功能
阅读量:7065 次
发布时间:2019-06-28

本文共 8567 字,大约阅读时间需要 28 分钟。

原文:

这个示例演示整合了Aran和微软的示例,无需修改即可运行。

支持识别,二维码/一维码,需要在包清单管理器勾选摄像头权限。

首先右键项目引用,打开Nuget包管理器搜索安装:ZXing.Net.Mobile

BarcodePage.xmal页面代码

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{    ///     /// 可用于自身或导航至 Frame 内部的空白页。    ///     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 active            if (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 active            if (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 page            await 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 threads            await 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;            }        }        ///         /// 解析二维码图片        ///         /// 图片        /// 
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
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(); } }}

 

转载地址:http://qdxll.baihongyu.com/

你可能感兴趣的文章
Java改环境变量把path修改了,win10系统修改JDK版本后配置环境变量不生效
查看>>
java编程cpu选i5还是i7,i5处理器和i7哪个好_i5和i7怎么选择-系统城
查看>>
php字典删除指定元素,完美解决python遍历删除字典里值为空的元素报错问题
查看>>
php strip_tags如何打开,php strip_tags函数怎么用
查看>>
name.php,rewrite_name.php
查看>>
修改php.ini如何生效,修改php.ini不生效
查看>>
oracle新建一个用户命令,oracle 外部用户创建(windows xp)
查看>>
后缀为php但是bin文件夹,PHP试题篇-1
查看>>
php面向对象笔试,2017秋招笔试题(php)部分题
查看>>
oracle视图恢复,第九章 Oracle恢复内部原理(恢复相关的 V$ 视图)
查看>>
oracle数据库匿名块,Oracle PL/SQL匿名块(二)
查看>>
oracle+weblogic漏洞,Oracle WebLogic远程命令执行漏洞预警
查看>>
中标普华linux桌面初始密码,中标普华桌面Linux3.0.1
查看>>
linux 可变 大小 磁盘6,Resize CentOS Linux hard drive partition (centos 6.3 调整LVS磁盘大小)...
查看>>
linux bash命令自动完成,RED HAT LINUX bash 自动补全命令安装
查看>>
linux服务器一直访问183.111.141.109,Linux服务器上11种网络连接状态
查看>>
linux内核编译找不到unistd,无法创建“arch/x86/syscalls/....../unistd_32.h”解决方法
查看>>
nobody nogroup linux vi nfs,nfs挂载后权限映射错误(nobody)的解决办法
查看>>
linux mlock源代码,LINUX系统调用mlock的代码分析-Read.DOC
查看>>
C语言编程求解传热学,中国石油大学计算传热学大作业2.pdf
查看>>