Android QR code feature implementation and long-press recognition QR code

Source: Internet
Author: User

First, the initial integration of the Zxing projectTwo-dimensional code recognition but in life everywhere, now basically all apps have two-dimensional code related operations, if the identification of the QR code from the beginning of development to do is still quite complex and troublesome, from the beginning of the development of the zero is not realistic, the best way is to use the existing open source projects, The most famous on GitHub is Zxing, which provides a QR code scanning solution for multiple platforms, and the open source project address is: https://github.com/zxing/zxing,we integrate zxing into our own projects today, and implement some of the two-dimensional code generation, scanning, long-press recognition QR code and other related operations:           1. Download the jar package that the Zxing project relies on:         is a: HTTP://REPO1.MAVEN.ORG/MAVEN2/COM/GOOGLE/ZXING/CORE/3.2.1/,Select Core-3.2.1.jar Download can, is currently the latest, the original existing will jar package import project can not run normally, only import source code, now there is no problem, under the open source project also has, you can always download the latest jar package, It is also ok to download a jar package that is Android-core-3.2.1.jar, or to copy only one of the classes inside the jar package into the project.

    2. Download the Zxing project:download on the Open source project, more than 100 m, this is very simple, don't tell me you won't.
Let's add zxing to our project, first copy the source code from the downloaded Zxing project to the project, and I'll integrate and implement the relevant features in Android Studio:The download after the decompression should look like this:                     Click on the android below in SRC to see the source copy into the project, in the resource file copy, and then change the androidmainfest of the declaration Activityde Shihou, because all is shorthand, now the package name changed, change it is good, And then for the project R file error A careful to get rid of OK, for a class error bookmarkpickeractivity, which is about 50 rows or so, Browser.bookmarks_uri this error, I'm going to change the build to 22, basically it's OK, like this:

      then basically run and you can start scanning the code.
Second, to obtain the core function of zxingThe function of this project is many, the project is very big, we need to take out the most core function, the net already has a lot of people to do, most are based on the first extract zxing, but that is based on Zxing1.5, 2.3 do, All we need to do is find an old one. Replace these classes with the latest zxing code. Below I give a ZXing3.1 package, contains the latest jar package and code, you can go to download, is provided by the doctor, GitHub already contains all of the previous mentioned changes (screen, warp distortion), with 3.1ZXing code update, while providing the encoding , decoding method, and extracting the scanning interface into XML (thanks to the open source author) for easy extension. Poke:Https://github.com/xuyisheng/ZXingLib
Three, to achieve scanning and long-press read and other functionsfirst Look, record the time did not put the mouse record entered, feeling is not very good, read out with the toast show, we will see it         to achieve the generation of two-dimensional code, such as reduced use can:         
Generate 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 pixel  Bitmap Bitmap = null;try {Bitmap = Bitmaputil.createqrcode (msg, 400);} catch (Writerexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}   Imageview.setimagebitmap (bitmap);

the resulting QR code is then placed in the appropriate location.


Now basically have long by two-dimensional code recognition, this implementation of my idea is that since the QR code scanning can be identified, then it is also able to parse the picture, then we can long press implementation of the current screen screenshot and then call the relevant class to parse:

Let's take a look at the screenshot code, and we'll look at it in comments:

This method status bar is blank and does not show the status bar Information private void Savecurrentimage () {//Gets the current screen size int width = GetWindow (). Getdecorview (). Getrootview (). getwidth (); int height = GetWindow (). Getdecorview (). Getrootview (). GetHeight ();//Generate images of the same size bitmap    Tembitmap = Bitmap.createbitmap (width, height, config.argb_8888); Locate the root layout of the current page view view = GetWindow (). Getdecorview (). Getrootview ();//Set Cache view.setdrawingcacheenabled (TRUE); View.builddrawingcache ();//Gets the picture of the current screen from the cache Tembitmap = View.getdrawingcache (); SimpleDateFormat df = new SimpleDateFormat ("Yyyymmddhhmmss"); time = Df.format (new Date ()); if (Environment.media_ Mounted.equals (Environment.getexternalstoragestate ())) {file = new file (Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/screen", Time + ". png"), if (!file.exists ()) {File.getparentfile (). mkdirs (); try { File.createnewfile ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}  FileOutputStream fos = null;  try {fos = new FileOutputStream (file); Tembitmap.compress (bitmap.compresSformat.png, FOS); Fos.flush (); Fos.close ();}  catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

above the screen and the current time for the name saved to the phone, we resolve the path can be passed directly into the parsing is good, I put the relevant classes to pass up, there are comments, we look at it:

Parse the QR code image and return the result encapsulated in the result object private Com.google.zxing.Result Parseqrcodebitmap (String bitmappath) {//Parse conversion type UTF-8  Hashtable<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 point the Bitmap is null, and after this code, Options.outwidth and Options.outheight are the width and height we want 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//above this practice, although the bitmap limit to the size we want, but did 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 from being less than or equal to 0} Options.injustdecodebounds = false;   Bitmap = Bitmapfactory.decodefile (Bitmappath, Options); Create a new Rgbluminancesource object that will bitmap the diagramTo 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;   }

according to Zxing's decoding rules, we need a bitmapluminancesource class and the only one that needs to be implemented.

Bitmapluminancesource inherits from Luminancesource this abstract class, needs to implement its construction method, its construction method needs to pass in the wide height, these two values refer to the picture width and height. The Getmatrix () method returns a byte array, which is an array of pixels of the image. GetRow (int y, byte[] row) is the literal meaning of getting a line of the image Pixel group. Where y is the pixel array of which row is needed.

The following is the complete Bitmapluminancesource class

public class Rgbluminancesource extends Luminancesource {private byte bitmappixels[];  Protected Rgbluminancesource (Bitmap Bitmap) {  super (Bitmap.getwidth (), Bitmap.getheight ());  First, to get the image of the pixel array content  int[] data = new Int[bitmap.getwidth () * bitmap.getheight ()];  This.bitmappixels = new Byte[bitmap.getwidth () * bitmap.getheight ()];  Bitmap.getpixels (data, 0, getwidth (), 0, 0, getwidth (), getheight ());  Converts an int array to a byte array, that is, the blue value portion of the pixel value as the discrimination content for  (int i = 0; i < data.length; i++) {  this.bitmappixels[i] = (byte) da Ta[i];  }  }  @Override public  byte[] Getmatrix () {  //Return our generated good pixel data return  bitmappixels;  }  @Override public  byte[] GetRow (int y, byte[] row) {  //here to get the pixel data for the specified row  system.arraycopy (bitmappixels, Y * GetWidth (), row, 0, getwidth ());  return row;  }  }

the byte[] array that gets the image pixel group content above refers to the pixel array of the picture, not the so-called bitmap converted to a byte array

The Bitmap object's Getpixels method can get an array of pixels, but it gets an array of type int. According to its API documentation, it is obtained by color, which is the pixel value. Each pixel value contains transparency, red, green, and blue. So White is 0xFFFFFFFF, Black is 0xff000000. directly from the int type to byte, the implementation of the equivalent of we only take its blue value part.


Getpixels The resulting pixel array is one-dimensional, that is, according to the image width row by pixel color value input. If you want the contents of a single-line pixel array, you can find the first pixel value of the row by Y*width, and the pixel content of the line can be obtained by copying the width of the following.

The last one is the Getmatrix () method, which is used to return the array of pixels to which our image is converted.

Finally, we will long press the stored picture path can be passed in, but note that when parsing open a thread, or ANR, basically achieve the majority of our needs to generate, read, identify most of the functions.

Later upload the source code to everyone, feel useful on the point of praise it ....


Android QR code feature implementation and long-press recognition QR code

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.