工业平板电脑,手持终端PDA,三防加固平板电脑,工业电脑

热线025-86113667/18014487552

通过摄像头扫描一维码/二维码(windows系统):相机软解码方案介绍

作者:手持三防加固平板电脑pad手持终端PDA定制专家    来源:www.dxe886.cn    发布时间:2019-08-07 12:52    浏览量:

现在一维码二维码的应用场景越来越多,通过摄像头来软解条码的方式也越来越多,下面研维工程师就为大家介绍一下通过摄像头扫描一维码/二维码(windows系统):相机软解码方案的具体实施步骤,希望对大家有所启迪。

1、首先打开VS2015开发环境,新建UWP工程,右键项目引用,打开Nuget包管理器搜索安装:ZXing.Net.Mobile

2、该工程基于
ZXing框架,应用部署于基于windows10系统的PDA手持设备之中,而非wince,请注意。

3、其中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();
        }
    }
}

4、其中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>

相关产品

8寸三防平板定制|8寸安

8寸三防平板定制|8寸安

8寸windows10系统手持终

8寸windows10系统手持终

7寸安卓二代证应用平

7寸安卓二代证应用平

4寸手持机PDA|手持pda条

4寸手持机PDA|手持pda条

10寸全坚固型平板电脑|

10寸全坚固型平板电脑|

6寸手持终端pda_安卓系

6寸手持终端pda_安卓系

7寸安卓级 uhf 平板电脑

7寸安卓级 uhf 平板电脑

带can接口工业级车载电

带can接口工业级车载电

企业分站 在线客服 :     服务热线: 025-86136252 / 15062244194     电子邮箱: [email protected]

公司地址:江苏省南京市未来网络小镇 sitemap

研维立足于行业终端技术的持续发展,自主研发全坚固工业三防加固平板电脑/工业安装平板电脑产品,包含加固手持终端pda(4寸/5寸/6寸),加固平板电脑pad(8寸/10寸),无风扇嵌入式工业平板电脑(8寸/10.1寸/10.4寸/11.6寸/12寸/15寸/17寸/19寸/21.5寸/32寸)。全系列手持终端pad-pda产品防护等级高达IP65~IP67, 美军标MIL- STD-810G防震耐冲击,包含2G/3G/4G,双频WiFi,蓝牙 4.0,北斗/GPS,NFC,一维码/二维码扫描,身份证,指纹等技术。并有多种配件可选,满足客户对工业、航空、航天、车载、警用、教育、勘探、渔牧业、金融等各行各业方案需求。

三防加固工业平板电脑厂家微信公众号
备案号:苏ICP备14059761号-5
主营区域:北京江苏浙江上海安徽山东四川广东福建天津河北河南湖南湖北陕西辽宁吉林江西黑龙江重庆
声明:(1)本站遵循《中华人民共和国广告法》,在标题、页面等文案描述中尽量规避违禁词、极限词,如还有违禁词、极限词,在此申明上述词汇表述全部失效,如客户咨询均表示默认此条款,不支持任何形式以违禁词、极限词等理由投诉或要求收取费用私下解决,特此申明!(2)除非研维公司另行申明,本网站内的所有产品、技术、软件、程序、数据及其他信息(包括文字、图标、图片、照片、音频、视频、图标、色彩组合、版面设计等)的所有权利(包括版权、商标权、专利权、商业秘密及其他相关权利)均归研维公司所有。未经研维公司的许可,任何人不得以包括通过机器人、人力等程序或设备监视、复制、传播、展示、镜像、上载、下载等方式擅自使用本网站的任何内容。一旦发现侵权行为,我司将立即进行证据保全并诉诸法律。
在线客服