Windows Phone 7 development skills [2] -- use the zxing library for one-dimensional/two-dimensional barcode scanning

Source: Internet
Author: User
Tags silverlight


The world's information is everywhere, and bar code is pervasive. Easy and fast generation and reading of bar code information has become a basic function of smartphones. How Can I scan the bar code in the window phone app? The first thing that comes to mind is to use a camera to read bar code images, binarization, and image processing. But as the saying goes, don't reinvent the wheel. Thanks to the powerful zxing Library [1], we can focus more on the implementation of the app's own functions. The zxing Library provides a wide range of one-dimensional/two-dimensional bar code reading functions, such as common EAN-13 and QR code. Zxing supports multiple typesProgramming LanguageSomeone has implemented the Silverlight version [2], which can be easily used in WP7 applications. This document describes how to use zxing from an instance.



To simplify the process, encapsulate a page barcode and switch from any page to the barcode page. The bar code is read automatically. After reading the code, switch to the result page. Encapsulation [3] is actually better, but it is inconvenient to use in my app. [3] is worth your reference.


I. Reference zxing


Create a wp7barcodescannerexample instance project, download the silverlightzxing library from [2], and add references to silverlight_zxing_core.dll. The following section interceptsCode, It can be seen that zxing is more convenient to use.


using com.google.zxing;
using com.google.zxing.oned;
using com.google.zxing.qrcode;
using com.google.zxing.common;

namespace WP7BarcodeScannerExample
{
     public partial class BarCode: PhoneApplicationPage
     {
         private Reader _reader = new EAN13Reader (); / or QRCodeReader ()

         private void ScanPreviewBuffer ()
         {

             Result result = _reader.decode (binBitmap);
             if (result! = null)
             {
                 // Read successfully, the result is result.Text
             }
         }
     }
} 


First, according to the bar code type to be read, taking the EAN-13 one-dimensional bar code as an example, initialize an ean13reader, and then decode the obtained image binbitmap to obtain the result.



 


Ii. photocamera


[4] I will explain in detail how to use photocamera. I will not go into details here. Note that the WP7 simulator does not support cameras, so this instance must run on a real machine.



 


Iii. barcode page


The main idea is to use videobrush to display the photocamera scene, focus at a fixed interval, read the image, and call the zxing encoding decoder for decoding, after the operation is successful, stop the scenario and read and switch to the result page.



Barcode. XAML


 
 
<Grid x:Name="LayoutRoot" Background="Transparent">
        <Rectangle HorizontalAlignment="Stretch" Name="frame" Stroke="Black" StrokeThickness="0" VerticalAlignment="Stretch">
            <Rectangle.Fill>
                <VideoBrush x:Name="_videoBrush">
                    <VideoBrush.RelativeTransform>
                        <CompositeTransform  
                            x:Name="_previewTransform" CenterX=".5" CenterY=".5" />
                    </VideoBrush.RelativeTransform>
                </VideoBrush>
            </Rectangle.Fill>
        </Rectangle>
</Grid>


Pay attention to videobrush, because the photocamera landscape is a landscape screen by default, you need to change it.



 



Barcode. XAML. CS:


using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices;
using com.google.zxing;
using com.google.zxing.oned;
using com.google.zxing.qrcode;
using com.google.zxing.common;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;

namespace WP7BarcodeScannerExample
{
    public partial class BarCode: PhoneApplicationPage
    {
        private PhotoCamera _photoCamera;
        private PhotoCameraLuminanceSource _luminance;
        private readonly DispatcherTimer _timer;
        //decoder
        private Reader _reader = null;

        public BarCode ()
        {
            InitializeComponent ();

            _timer = new DispatcherTimer ();
            _timer.Interval = TimeSpan.FromMilliseconds (250);
            // call the read function at 250ms interval
            _timer.Tick + = (o, arg) => ScanPreviewBuffer ();
        }

        protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
        {
            string type = "";
            
            if (NavigationContext.QueryString.TryGetValue ("type", out type) && type == "qrcode")
            {
                _reader = new QRCodeReader ();
            }
            else
            {
                _reader = new EAN13Reader ();
            }

            _photoCamera = new PhotoCamera ();
            _photoCamera.Initialized + = new EventHandler <CameraOperationCompletedEventArgs> (cam_Initialized);
            _videoBrush.SetSource (_photoCamera);
            base.OnNavigatedTo (e);
        }

        protected override void OnNavigatingFrom (System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (_photoCamera! = null)
            {
                _timer.Stop ();
                _photoCamera.CancelFocus ();
                _photoCamera.Dispose ();
            }
            
            base.OnNavigatingFrom (e);
        }

        void cam_Initialized (object sender, CameraOperationCompletedEventArgs e)
        {
            int width = Convert.ToInt32 (_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32 (_photoCamera.PreviewResolution.Height);
            _luminance = new PhotoCameraLuminanceSource (width, height);
            
            Dispatcher.BeginInvoke (() =>
            {
                _previewTransform.Rotation = _photoCamera.Orientation;
                _timer.Start ();
            });
            _photoCamera.FlashMode = FlashMode.Auto;
            _photoCamera.Focus ();
        }

        private void ScanPreviewBuffer ()
        {
            try
            {
                _photoCamera.GetPreviewBufferY (_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer (_luminance);
                var binBitmap = new BinaryBitmap (binarizer);
                Result result = _reader.decode (binBitmap);
                if (result! = null)
                {
                    _timer.Stop ();
                    Dispatcher.BeginInvoke (() =>
                    {
                        // Read successfully, the result is stored in result.Text
                    });
                }
                else
                {
                    _photoCamera.Focus ();
                }
            }
            catch
            {
            }
        }
    }
} 


Note:



1. Check the scanpreviewbuffer () function and call _ reader to decode the binarization image. If the result is not empty, the decoding is successful and the result is stored in the result. text, you can use multiple methods to pass to other pages of your application.



2. When navigate to the barcode page, if the querystring parameter is not included, ean13reader is used for one-dimensional Barcode recognition by default. If type = qrcode is included, qrcodereader is used for two-dimensional Barcode recognition.



 


Iv. Experience


In general, the bar code scanning process for this instance is relatively fast. However, the scanning process requires repeated focus, and the speed is relatively slow when the light and other conditions are poor. For a better user experience, some auxiliary functions need to be added during the barcode scanning process. For example, if an indicator box is displayed on the page of the view, it is marked in red at the beginning and green after the reading is successful. After the reading is successful, stop the scene retrieval and obtain the current image for display. This prevents some abrupt changes from directly switching to the structure page. In this example, the implementation of the content is not good. It is just an example. You can complete it with many possibilities.



 


V. instance code


The instance code is stored on GitHub.



 


Vi. References


[1]: zxing, http://code.google.com/p/zxing/



[2]: Silverlight zxing, Windows Phone 7 Silverlight zxing barcode scanning library, http://silverlightzxing.codeplex.com/



[3]: Stephen hertrich, WP7: real-time video scan a barcode/QR code in your app using zxing Lib, http://blogs.msdn.com/ B /stephe/archive/2011/11/07/wp7-real-time-video-scan-a-barcode-qr-code-in-your-app-using-zxing-lib.aspx



[4]: Matt stroshane, using cameras in your Windows Phone application, http://msdn.microsoft.com/en-us/magazine/hh708750.aspx



[5]: QR code scanning on Windows Phone 7.5 using zxlib, http://jonas.follesoe.no/2011/07/22/qr-code-scanning-on-windows-phone-75-using-zxlib/


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.