A method for using zxing to identify barcodes and two-dimensional codes on Android _android

Source: Internet
Author: User

At present, more and more mobile phones have the ability to shoot autofocus, which means that these phones can have the function of barcode scanning. mobile phone with barcode scanning function, can optimize shopping flow, fast storage of electronic business cards (two-dimensional code) and so on.

The example described in this paper uses the Zxing 1.6 to realize barcode/two-D code recognition. Zxing is a very classic barcode/two-D code recognition of open Source Library, long ago, there are developers on the J2ME use of zxing, but need to support the JSR-234 specification (autofocus) of the mobile phone to play its power, And there are already a lot of Android phones with autofocus capabilities.

The results of this code run are as follows: You can't intercept Surfaceview's real-time images using 91 phone-assistant Screenshots

In this paper, the core of ZXing1.6 is used, that is, to copy the SRC under/zxing-1.6/core/to cover the engineering SRC, and also to use the Planaryuvluminancesource.java under/zxing-1.6/android/.

Note here:/zxing-1.6/android/is the source of the barcodescanner, this procedure is equivalent to the barcodescanner of the compact version, only to retain the most basic recognition function.

This article complete source code click here to download locally.

Source directory results as shown below, Checksumexception.java there are many source files, screenshots are not listed:

This article example must open the camera and autofocus permissions, otherwise the startup will report an exception, the use of the following permissions:

<uses-permission android:name= "Android.permission.CAMERA" ></uses-permission>
< Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
< Uses-feature android:name= "Android.hardware.camera"/>
<uses-feature android:name= " Android.hardware.camera.autofocus "/>

Main.xml source code as follows, Main.xml must use framelayout to overlap the control to achieve the "scope box" effect:

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout android:id= "@+id/framelayout01"
 Fill_parent "android:layout_height=" fill_parent "xmlns:android=" http://schemas.android.com/apk/res/android "> <surfaceview android:layout_height= "fill_parent" android:id= @+id/sfvcamera "android:layout_width=" fill_parent "></SurfaceView> <relativelayout android:id=" @+id/relativelayout01 "android:layout_height=" Fill_ Parent "android:layout_width=" fill_parent "> <imageview android:id=" @+id/imageview01 "android:layout_height=" 100dip "android:layout_width=" 160dip "></ImageView> <view android:layout_centervertical=" true "Android: Layout_centerhorizontal= "true" android:layout_width= "300dip" android:background= "#55FF6666" android:id= "@+id/
 Centerview "android:layout_height=" 180dip "></View> <textview android:layout_centerhorizontal=" true " Android:layout_width= "Wrap_content" android:layout_below= "@+id/centerview" Android:layout_height= "Wrap_content" android:text= "Scanning ..." android:id= "@+id/txtscanresult" android:textcolor= "#FF000000"

 ></TextView> </RelativeLayout> </FrameLayout>

Testcamera.java is the main class, responsible for controlling camera and decoding the image, the source code is as follows:

Package Com.testcamera;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import Com.google.zxing.BinaryBitmap;
Import Com.google.zxing.MultiFormatReader;
Import Com.google.zxing.Result;
Import Com.google.zxing.Android.PlanarYUVLuminanceSource;
Import Com.google.zxing.common.HybridBinarizer;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.hardware.Camera;
Import Android.os.Bundle;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.widget.ImageView;
Import Android.widget.TextView; The public class Testcamera extends activity {/** called the ' when ' is the ' The activity ' is a-created. Private Surfaceview Sfvcame
 Ra
 Private Sfhcamera Sfhcamera;
 Private ImageView Imgview;
 Private View Centerview;
 Private TextView Txtscanresult;
 Private Timer Mtimer;
 Private Mytimertask Mtimertask;
 In accordance with the standard HVGA final static int width = 480;
 Final static int height = 320;
 int Dstleft, Dsttop, Dstwidth, dstheight; @Override public void OnCreate (Bundle savEdinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main);
 This.settitle ("Android barcode/Two D Code identification demo-----HELLOGV");
 Imgview = (ImageView) This.findviewbyid (R.ID.IMAGEVIEW01);
 Centerview = (View) This.findviewbyid (R.id.centerview);
 Sfvcamera = (Surfaceview) This.findviewbyid (R.id.sfvcamera);
 Sfhcamera = new Sfhcamera (Sfvcamera.getholder (), width, height, previewcallback);
 txtscanresult= (TextView) This.findviewbyid (R.id.txtscanresult);
 Initialize Timer Mtimer = new timer ();
 Mtimertask = new Mytimertask ();
 Mtimer.schedule (mtimertask, 0, 80); Class Mytimertask extends TimerTask {@Override public void run () {if (Dstleft = = 0) {//only assigned once dstleft = Centerview
 . GetLeft () * Width/getwindowmanager (). Getdefaultdisplay (). GetWidth ();
 Dsttop = Centerview.gettop () * Height/getwindowmanager (). Getdefaultdisplay (). GetHeight ();
 Dstwidth = (Centerview.getright ()-Centerview.getleft ()) * Width/getwindowmanager (). Getdefaultdisplay (). GetWidth (); Dstheight = (cenTerview.getbottom ()-centerview.gettop ()) * Height/getwindowmanager (). Getdefaultdisplay (). GetHeight ();
 } sfhcamera.autofocusandpreviewcallback (); }/** * Auto focus output picture/private Camera.previewcallback previewcallback = new Camera.previewcallback () {@Override PU Blic void Onpreviewframe (byte[] data, Camera arg1) {//Get the specified range of frames from the planaryuvluminancesource Source = new Planaryuvlumina
 Ncesource (data, width, height, dstleft, dsttop, Dstwidth, dstheight);
 Get Gray scale Bitmap Mbitmap = Source.rendercroppedgreyscalebitmap ();
 Displays grayscale Imgview.setimagebitmap (MBITMAP);
 Binarybitmap bitmap = new Binarybitmap (new Hybridbinarizer (source));
 Multiformatreader reader = new Multiformatreader ();
 try {result = Reader.decode (bitmap);
 String strresult = "Barcodeformat:" + Result.getbarcodeformat (). toString () + "text:" + result.gettext ();
 Txtscanresult.settext (strresult);
 catch (Exception e) {txtscanresult.settext ("scanning");
}
 }
 };

 }

Sfhcamera.java is the camera control class, the source code is as follows:

Package Com.testcamera;
Import java.io.IOException;
Import Android.graphics.PixelFormat;
Import Android.hardware.Camera;
Import Android.util.Log;
Import Android.view.SurfaceHolder;
 public class Sfhcamera implements surfaceholder.callback{private Surfaceholder holder = null;
 Private Camera Mcamera;
 private int width,height;
 Private Camera.previewcallback Previewcallback; 
 Public Sfhcamera (Surfaceholder holder,int w,int h,camera.previewcallback previewcallback) {this.holder = holder; 
 This.holder.addCallback (this);
  This.holder.setType (surfaceholder.surface_type_push_buffers);
  Width=w;
  Height=h;
 This.previewcallback=previewcallback;  @Override public void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {camera.parameters Parameters 
  = Mcamera.getparameters ();
  Parameters.setpreviewsize (width, height);//Set Dimension Parameters.setpictureformat (Pixelformat.jpeg); 
  Mcamera.setparameters (parameters); Mcamera.startpreview ()//Start preview log.e ("Camera", "SurfaCechanged "); @Override public void surfacecreated (Surfaceholder arg0) {Mcamera = Camera.open ();/start service try {Mcamera.setpre
  Viewdisplay (Holder)//Set preview LOG.E ("Camera", "surfacecreated"); 
  catch (IOException e) {mcamera.release ();//free Mcamera = null;
 @Override public void surfacedestroyed (Surfaceholder arg0) {mcamera.setpreviewcallback (null);
  Mcamera.stoppreview ()//stop preview Mcamera = null;
 LOG.E ("Camera", "surfacedestroyed"); /** * AF and callback Camera.previewcallback */public void Autofocusandpreviewcallback () {if (mcamera!=null) Mcamera.auto
 Focus (Mautofocuscallback); 
  /** * Auto Focus/private Camera.autofocuscallback Mautofocuscallback = new Camera.autofocuscallback () {@Override public void Onautofocus (Boolean success, Camera Camera) {if (success) {//focus succeeded, callback Camera.previewcallback Mcame 
   Ra.setoneshotpreviewcallback (Previewcallback);
} 
  } 
 };

 }

The Camera.previewcallback previewcallback of Testcamera.java is the logical core of the whole program, which is invoked as a callback function to Sfhcamera.java's internal camera class.

PS: This site also provides a very powerful two-dimensional code generation tool, interested friends can refer to:

Http://tools.jb51.net/transcoding/jb51qrcode

I hope this example will help you learn about Android programming.

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.