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

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

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

BarcodePage.xmal页面代码

<Page
x: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 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();
_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();
}
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, ); 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();
}
}
}

Win10 UWP开发:摄像头扫描二维码/一维码功能的更多相关文章

  1. Android开发——通过扫描二维码,打开或者下载Android应用

    Android开发——通过扫描二维码,打开或者下载Android应用   在实现这个功能的时候,被不同的浏览器折磨的胃疼,最后实现了勉强能用,也查考了一下其他人的博客 android实现通过浏览器点击 ...

  2. h5端呼起摄像头扫描二维码并解析

    2016年6月29日补充: 最近做了一些与表单相关的项目,使用了h5的input控件,在使用过程中遇到了很多的坑.也包括与这篇文章相关的. 首先我们应该知道使用h5新提供的属性getUserMedia ...

  3. 使用vue做移动app时,调用摄像头扫描二维码

    现在前端技术发展飞快,前端都能做app了,那么项目中,也会遇到调用安卓手机基层的一些功能,比如调用摄像头,完成扫描二维码功能 下面我就为大家讲解一下,我在项目中调用这功能的过程. 首先我们需要一个中间 ...

  4. Android开发之扫描二维码开发

    原贴地址:http://www.cnblogs.com/Fndroid/p/5540688.html 二维码其实有很多种,但是我们常见的微信使用的是一种叫做QRCode的二维码,像下面这样的,可以放心 ...

  5. 在WPF中开启摄像头扫描二维码(Media+Zxing)

    近两天项目中需要添加一个功能,是根据摄像头来读取二维码信息,然后根据读出来的信息来和数据库中进行对比显示数据. 选择技术Zxing.WPFMediaKit.基本的原理就是让WPFmediaKit来对摄 ...

  6. C# winfrom调用摄像头扫描二维码(完整版)

    前段时间看到一篇博客,是这个功能的,参考了那篇博客写了这个功能玩一玩,没有做商业用途.发现他的代码给的有些描述不清晰的,我就自己整理一下发出来记录一下. 参考博客链接:https://www.cnbl ...

  7. 打开手机摄像头扫描二维码或条形码全部操作(代码写的不好,请提出指教,共同进步,我只是一个Android的小白)

    (1)下载二维码的库源码 链接:http://pan.baidu.com/s/1pKQyw2n 密码:r5bv 下载完成后打开可以看到 libzxing 的文件夹,最后添加进 Android  Stu ...

  8. Vue-cli4 唤醒摄像头扫描二维码

    <template> <div class="scan"> <div id="bcid"> <div id=" ...

  9. Ionic2学习笔记(10):扫描二维码

    作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5575843.html 时间:6/11/2016     说明: 在本文发表的时候(2016-06-1 ...

随机推荐

  1. 提升Android编译速度

    Android codebase都非常大.编译一次都须要花非常多时间.假设是preloader/lk/bootimage还好,可是Android的话都是非常久. 实际上这个编译时间还是能够进一步缩短! ...

  2. Android之——AIDL深入

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47071927 在上一篇博文<Android之--AIDL小结>中,我们 ...

  3. Codeforces 480B Long Jumps 规律题

    题目链接:点击打开链接 题意: 输出n l x y 有一根直尺长度为l 上面有n个刻度. 以下n个数字是距离开头的长度(保证第一个数字是0,最后一个数字是l) 要使得 直尺中存在某2个刻度的距离为x ...

  4. 亿部书城李柯毅:Testin云測可大幅提升产品质量 值得推荐!

    亿部书城李柯毅:Testin云測可大幅提升产品质量 值得推荐! 2014/10/13 · Testin · 开发人员訪谈 成立于2010年的亿部书城.其主营业务为移动增值业务及数字出版业务,由中央部委 ...

  5. Java小白手记2:一些名词解释

    看到<Java 征途:行者的地图> ,这是一篇有关java学习路径文章.对我等Java小白有指引作用.里面提到了一些基本的名词术语,有些我知道,有些不知道,再补上一些自己曾觉得模糊的,记录 ...

  6. 生成 hibernate 映射文件和实体类

    创建web工程,使用Hibernate的时候,在工程里一个一个创建实体类太麻烦,浪费时间,现在教大家如何用MyEclipse自动生成Hibernate映射文件及实体类 方法/步骤   创建数据库,创建 ...

  7. css3动画应用-音乐唱片旋转播放特效

    css3动画应用-音乐唱片旋转播放特效 核心点: 1.设置图片为圆形居中,使图片一直不停旋转. 2.文字标题(潘玮柏--反转地球)一直从左到右不停循环移动. 3.点击图标,音乐暂停,图片停止旋转:点击 ...

  8. JS数组array常用方法

    JS数组array常用方法 1.检测数组 1)检测对象是否为数组,使用instanceof 操作符 if(value instanceof Array) { //对数组执行某些操作 } 2)获取对象的 ...

  9. 机器学习: KNN--python

    今天介绍机器学习中比较常见的一种分类算法,K-NN,NN 就是 Nearest Neighbors, 也就是最近邻的意思,这是一种有监督的分类算法,给定一个 test sample, 计算这个 tes ...

  10. 洛谷 P1072 Hankson 的趣味题 —— 质因数分解

    题目:https://www.luogu.org/problemnew/show/P1072 满足条件的数 x 一定是 a1 的倍数,b1 的因数,a0/a1 与 x/a1 互质,b1/b0 与 b1 ...