Win10 UWP开发:摄像头扫描二维码/一维码功能

原文:Win10 UWP开发:摄像头扫描二维码/一维码功能

这个示例演示整合了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(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;
            }
        }

        /// <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();
        }
    }
}

 

时间: 2025-01-21 02:19:36

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

ios开发-支付宝扫描二维码支付

问题描述 支付宝扫描二维码支付 支付宝扫描二维码的原理是什么,用扫描软件扫描支付宝二维码得到的是一串网址,怎样把这个网址用支付宝打开来实现支付? 解决方案 购物的时候,向支付宝发送一个支付请求,支付宝记录金额.收款方.商品名等信息以及安全校验等信息,然后产生url 扫描二维码,就可以根据它指向的url查到这些信息,然后从支付宝扣款完成支付. 解决方案二: 这都属于二维码处理,要看源码实现的话,google有个开源项目zxing就是处理二维码的: 至于如何让支付宝打开 来支付,打开的话androi

扫描二维码得红包功能实现

问题描述 扫描二维码得红包功能实现 请教各位大哥大姐,那个扫描二维码得红包,微信文档怎么没有这个呀?谢谢各位 解决方案 iOS开发之扫描二维码功能的实现 解决方案二: 已上传,PHP实现的http://download.csdn.net/detail/xin_o/9529644

java-web 网站扫描二维码,JAVA开发的

问题描述 web 网站扫描二维码,JAVA开发的 网页怎么调用手机,PAD摄像头扫二维码(不是android,是JAVAweb项目) 解决方案 html5拍照上传http://bbs.9ria.com/thread-215588-1-1.htmlhttp://blog.163.com/very_apple/blog/static/277592362014429114744615/ 至于识别二维码,可以用zxing 解决方案二: 你的网站怎么扫别人的二维码,别人有吗,你能得到吗 解决方案三: 外网

微信公众平台java开发关于微信扫描二维码的问题

问题描述 微信公众平台java开发关于微信扫描二维码的问题 某微信用户已经关注了我的公众号,然后他扫描了我公众平台的一个二维码,我想获取他的用户名,要怎么做?扫描二维码,是一个触发事件吗? 感谢各位了! 解决方案 他如果仅仅只是扫描的话,你是看不到他的用户名的.但是如果他关注了你的公众号,你在公众平台的用户管理里,是可以看到他的用户名信息的.希望能够帮到你. 解决方案二: 这个问题我自己研究的差不多了.用微信自己的扫一扫功能是不可能将事件推送给自己的公众平台的,我想它是推送事件给微信的公众平台了

html5怎么调用手机摄像头并且扫描二维码?

问题描述 html5怎么调用手机摄像头并且扫描二维码? 现在在做的一个项目需要做一个手机浏览器上扫描二维码的功能,自己在网上找了很多,但还是不行,求大神指点.谢谢!谢谢! 解决方案 http://www.jb51.net/html5/422307.htmlhttp://download.csdn.net/download/xuewufeifang/9256945 解决方案二: appcan和hbuilder都有解决办法,你查查看

摄像头-ZBar二维码扫描,无法连续点击扫描

问题描述 ZBar二维码扫描,无法连续点击扫描 大概第三次的时候,进入摄像头的速度特别的慢..如何解决? 附上代码: CameraViewController *camera=[CameraViewController new] ; [self presentViewController:camera animated:YES completion:nil]; [camera release]; camera 这部分是用ZBarReaderView自定义的界面... 解决方案 ZBar 二维码扫

。net怎么通过手机来扫描二维码

问题描述 怎么通过点击手机网页上的按钮对二维码或条形码进行扫描,再把扫到的信息返回给页面. 解决方案 解决方案二:点手机网页二维码,是什么东西解决方案三:扫描二维码的机制,必须是一个独立设计开发的应用,它是不断地录制视频的,并且不断地识别图像.你需要自己写几行代码,目前还没有什么插件直接用在js中调用.先把你的问题具体化,看出你确实在搞这个设计开发,而不是随便抄点东西.再说.解决方案四:HTML5+JS手机端的浏览器虽多数都已支持html5,但实际效果可能并不完全一致,不过你可以试试的.http

iOS中 扫描二维码/生成二维码详解

最近大家总是问我有没有关于二维码的demo,为了满足大家的需求,特此研究了一番,希望能帮到大家! 每日更新关注:http://weibo.com/hanjunqiang  新浪微博 指示根视图: [objc] view plain copy self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[SecondViewController new]];   每日更新关注:

iOS中 扫描二维码/生成二维码详解 韩俊强的博客

最近大家总是问我有没有关于二维码的demo,为了满足大家的需求,特此研究了一番,希望能帮到大家! 每日更新关注:http://weibo.com/hanjunqiang  新浪微博 指示根视图: self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[SecondViewController new]]; 每日更新关注:http://weibo.com/hanjunqi