Android zxing Two-dimensional code generation and recognition

Source: Internet
Author: User
Tags image processing library

Two-dimensional code:

It is a black-and-white graph which is distributed in the plane (two-dimensional direction) by a certain geometry to record the data symbol information;

The concept of 0-and 1-bit streams, which compose the logic basis of the computer, is used to represent the literal numerical information by using several geometric shapes corresponding to the binary system, and the automatic reading is realized by the image input device or photoelectric scanning device to realize automatic information processing.

The QR code can express information in both horizontal and vertical two directions, so it can express a large amount of information in a very small area.

The advantage of QR code relative to bar code is to save space;


Zxing Introduction:

Zxing is an open source, Java-implemented, multi-format 1d/2d barcode Image processing library that contains interfaces that are linked to other languages.

Zxing can be implemented using the phone's built-in camera to complete the barcode and QR code scanning and decoding.

The zxing can encode and decode barcodes and QR codes.

The formats currently supported by Zxing are as follows:

Upc-a,upc-e

Ean-8,ean-13

39 yards

93 yards

Code 128

QR code


Use of zxing on Android:

This can be used in two ways:

1. Put the Zxing jar package into the project Lib library, and then copy the corresponding class source to the project, the whole folder copy was also very fast;

2. The project has been completed zxing as a dependent library of the current project, and then directly to use it;




Below is an example of the following three functions:

1. Generate two-dimensional code;

2. Parsing two-dimensional code images;

3. Scan the QR code and parse it;


The end result is this:



Before we create a new project, we must import the dependent library into eclipse, relying on the original project folder of the library I have packaged, the article at the end of the link can be downloaded.


Identification of the QR code (image recognition) This function requires a class called Rgbluminancesource, the contents of this class are as follows:

Import Java.io.filenotfoundexception;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Com.google.zxing.luminancesource;public class Rgbluminancesource extends Luminancesource {private final byte[] Luminances;public Rgbluminancesource (Bitmap Bitmap) {super (Bitmap.getwidth (), Bitmap.getheight ());//Get picture of the width of the high int width = bitmap.getwidth (); int height = bitmap.getheight ();//Get Picture of pixel int[] pixels = new Int[width * Height];//bitmap.getpix Els (pixels, 0, width, 0, 0, width, height);//In order to measure the pure decoding speed, we will complete the image in front of the grayscale array, which is the same channel//Yuvluminancesource in the real application. Get the pixel size of the number of bytes luminances = new Byte[width * height];//get the picture per dot pixel color for (int y = 0; y < height; y++) {int offset = y * width; for (int x = 0; x < width; + +) {int pixel = Pixels[offset + x];int r = (pixel >> +) & 0xff;int g = (Pixel & Gt;> 8) & 0xff;int B = pixel & 0xff;//When a 1.3 color value is the same, the corresponding byte corresponding space is assigned its value if (r = = g && g = = b) {LUMINANCES[OFFSE T + x] = (byte) r;} Other cases the byte space corresponding assignment is: else {luminances[offset + x] = (byte) ((R + G + G + B) >> 2);}}} Public Rgbluminancesource (String path) throws FileNotFoundException {This (LoadBitmap (path));} @Overridepublic byte[] Getmatrix () {return luminances;} @Overridepublic byte[] GetRow (int arg0, byte[] arg1) {if (arg0 < 0 | | arg0 >= getheight ()) {throw new Illegalargumen Texception ("Requested row is outside the image:" + arg0);} int width = getwidth (), if (arg1 = = NULL | | Arg1.length < width) {arg1 = new byte[width];} System.arraycopy (luminances, arg0 * width, arg1, 0, width); return arg1;} private static Bitmap LoadBitmap (String path) throws FileNotFoundException {Bitmap Bitmap = Bitmapfactory.decodefile ( Path), if (bitmap = = null) {throw new FileNotFoundException ("couldn ' t open" + path);} return bitmap;}}

Next, there is a special note about the configuration section of manifest, which requires permission to join, and a declaration that relies on an activity in the library:

    <uses-permission android:name= "Android.permission.CAMERA"/> <uses-permission android:name= "Android.permi Ssion. Vibrate "/> <uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/> <uses-permissio n android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/> <application android:allowbackup=" true "Android:ic on= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > < Activity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <activity android:name=" Com.zxing.activity.Ca PtureActivity "></activity> </application> 

OK, now let's look at how the activity class you write implements the three functions described above:

Import Java.util.hashtable;import Com.google.zxing.binarybitmap;import Com.google.zxing.decodehinttype;import Com.google.zxing.result;import Com.google.zxing.common.hybridbinarizer;import Com.google.zxing.qrcode.qrcodereader;import Com.zxing.activity.captureactivity;import Com.zxing.encoding.encodinghandler;import Android.annotation.suppresslint;import Android.app.Activity;import Android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.provider.mediastore;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.toast;public class Mainactivity extends Activity implements Onclicklistener {private static final int choose_pic = 0;private static final int photo_pic = 1;private EditText contented Ittext = null;private ImageView Qrcodeimageview = null;private String imgpath = null; @OverrideprotecTed void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Setupviews ();} private void Setupviews () {contentedittext = (EditText) Findviewbyid (R.ID.EDITTEXT1); Findviewbyid (R.id.button1). Setonclicklistener (This), Findviewbyid (R.id.button2) Setonclicklistener (this); Findviewbyid (R.id.button3). Setonclicklistener (this); Qrcodeimageview = (ImageView) Findviewbyid (R.ID.IMG1);} Parse two-dimensional code image, return result encapsulated in result object private Com.google.zxing.Result Parseqrcodebitmap (String bitmappath) {// Parse conversion type Utf-8hashtable<decodehinttype, string> hints = new Hashtable<decodehinttype, string> (); Hints.put ( Decodehinttype.character_set, "Utf-8");//Get to the image to be parsed bitmapfactory.options Options = new Bitmapfactory.options (); If we set Injustdecodebounds to True, then Bitmapfactory.decodefile (String path, Options opt)//will not really return a bitmap to you, it will simply put it wide, High fetch back to you options.injustdecodebounds = true;//at this time the bitmap is null, after this code, Options.outwidth and Options.outheight is what we want and high bitmap bitmap = bitmapFactory.decodefile (bitmappath,options);//We now want to take out the picture of the side length (QR code picture is square) set to 400 pixels/**options.outheight = 400;o Ptions.outwidth = 400;options.injustdecodebounds = False;bitmap = Bitmapfactory.decodefile (BitmapPath, options); */// This approach, although the bitmap limit to the size we want, but does not save memory, if you want to save memory, we also need to use insimplesize this property Options.insamplesize = options.outheight/400 if (options.insamplesize <= 0) {options.insamplesize = 1;//prevent its value less than or equal to 0}/** * Secondary save memory Setting * * Options.inpreferredconfig = B Itmap.    config.argb_4444;  The default is Bitmap.Config.ARGB_8888 * options.inpurgeable = true;  * Options.ininputshareable = true; */options.injustdecodebounds = False;bitmap = Bitmapfactory.decodefile (Bitmappath, Options); Create a new Rgbluminancesource object and pass the bitmap picture to this object Rgbluminancesource Rgbluminancesource = new Rgbluminancesource (bitmap);// Convert picture to binary picture binarybitmap Binarybitmap = new Binarybitmap (new Hybridbinarizer (Rgbluminancesource));// Initialize Parse object Qrcodereader reader = new Qrcodereader ();//start parsing result = Null;try {result = Reader.decode (binarybitmap, hints);} catch (Exception e) {//Todo:handle exception}return result;} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult ( Requestcode, ResultCode, data) Imgpath = null;if (ResultCode = RESULT_OK) {switch (requestcode) {case choose_pic:string[ ] proj = new String[]{mediastore.images.media.data}; cursor cursor = MainActivity.this.getContentResolver (). Query (Data.getdata (), proj, NULL, NULL, NULL); Cursor.movetofirst ()) {int columnindex = Cursor.getcolumnindex (MediaStore.Images.Media.DATA); System.out.println (columnindex);//Gets the absolute path to the user-selected QR code picture Imgpath = cursor.getstring (columnindex);} Cursor.close ();//Get parse result ret = Parseqrcodebitmap (Imgpath); Toast.maketext (Mainactivity.this, "parse Result:" + ret.tostring (), Toast.length_long). Show (); Break;case photo_pic:string result = Data.getextras (). getString ("result"); Toast.maketext (Mainactivity.this, "parse Result:" + result, Toast.length_long). Show (); break;default:break;}}} @SuppressLint ("Inlinedapi") @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.button1://gets the contents of the interface input string content = Contentedittext.gettext (). toString ();//Determine if the contents are empty if (null = = Content | | ". Equals (content)) {Toast.maketext (Mainactivity.this," Enter the content to be written to the QR code ... ", Toast.length_short). Show (); return;} try {//Generate a two-dimensional code picture, the first parameter is the content of the QR code, the second parameter is the side length of the square picture, the unit is pixels bitmap qrcodebitmap = encodinghandler.createqrcode (content, 400); Qrcodeimageview.setimagebitmap (QRCODEBITMAP);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Break;case r.id.button2://Jump to the Image selection screen to select a QR code image Intent Intent1 = new Intent ();//if (Android.os.Build.VERSION.SDK_INT <) {//intent1.setaction (intent.action_get_content);//}else{//intent1.setaction (intent.action_open_document );//}intent1.setaction (Intent.action_pick); Intent1.settype ("image/*"); Intent Intent2 = Intent.createchooser ( Intent1, "Select QR code image"); Startactivityforresult (Intent2, choose_pic); Break;case r.id.button3://jump to the photo screen scan QR Code intent Intent3 = new Intent (Mainactivity.this, CaptureActivity.class); Startactivityforresult (Intent3, photo_pic); break;default:break;}} 

Finally, the link to all the code packages is attached, and the students who need it can be downloaded and imported into their eclipse:

Android Zxing Demo


Android zxing Two-dimensional code generation and recognition

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.