Playing the QR code generation and recognition of Android

Source: Internet
Author: User

QR Code, we also called QRCODE,QR Express response fast response, in many apps we can see the figure of two-dimensional code, the most common is. So today we'll see how to integrate the scanning and generation of QR codes into our own app. OK, no more nonsense, let's start.

The use of two-dimensional code I mainly want to be divided into two parts to introduce, part is the generation of two-dimensional code, where the knowledge points are very simple, there is a part of the identification of two-dimensional code, here a little trouble, but careful to do is actually very simple. Development and use of QR codes most of us use the Zxing library provided by Google, we need to download the core Jar packageFirst, if we just want to generate a QR code then this is enough, but if we want to do the QR code recognition, Then we need to continue to add the open source project on GitHub on the basis of the previous one, which we'll talk about later.

1. Generation of two-dimensional code

Let's take a look at the first one:


1.1 Preparatory work

If we only do the two-dimensional code generation, then we just need to add the core jar package, as follows:


1.2 Two-dimensional code generation

OK, after adding the jar package we can begin to write two-dimensional code generation code, the QR code itself is a bitmap picture, so we are here mainly to see how to generate this picture, I add a button and a ImageView in the main interface, A two-dimensional code image is displayed on the ImageView when the button is clicked. The layout is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout    xmlns:android= "http://schemas.android.com/apk /res/android "    xmlns:tools=" Http://schemas.android.com/tools "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    tools:context= "org.mobiletrain.qrwriter.MainActivity" >    < Button        android:layout_width= "wrap_content"        android:layout_height= "wrap_content"        android:onclick= " Generate "        android:text=" generates two-dimensional code "/>    <imageview        android:id="        @+id/iv "android:layout_width = "256DP"        android:layout_height= "256DP"        android:layout_centerinparent= "true"/></relativelayout >

When I click on the button to generate a two-dimensional code image, then we will take a look at the core code to generate a two-dimensional code image:

Private Bitmap Generatebitmap (String content,int width, int height) {Qrcodewriter qrcodewriter = new Qrcodewriter (        );        Map<encodehinttype, string> hints = new hashmap<> ();        Hints.put (Encodehinttype.character_set, "utf-8");            try {Bitmatrix encode = qrcodewriter.encode (content, Barcodeformat.qr_code, width, height, hints);            int[] pixels = new int[width * height]; for (int i = 0, i < height; i++) {for (int j = 0; J < width; j + +) {if (encode.ge                    T (j, I)) {Pixels[i * width + j] = 0x00000000;                    } else {Pixels[i * width + j] = 0xFFFFFFFF; }}} return Bitmap.createbitmap (pixels, 0, width, width, height, Bitmap.Config.RGB_5        65);        } catch (Writerexception e) {e.printstacktrace ();    } return null; }

First of all, this method receives three parameters, these three parameters represent the generation of two-dimensional code text content (which text you want to use a two-dimensional code image), the second and the third parameter represents the generated two-dimensional code picture width and height respectively. Here, we first want to obtain a qrcodewriter instance, in which there is a method called encode, the method to encode the text content, the method has five parameters, the first parameter represents the generation of two-dimensional code text content, the second parameter represents the encoding format, The third parameter represents the width of the generated QR code, the fourth parameter represents the height of the generated two-dimensional code, the fifth parameter is optional, can be used to set the encoding of the text, the return value of the Encode method is a bitmatrix, you can interpret Bitmatrix as a two-dimensional array, Each element of this two-dimensional array represents whether a pixel has data. OK, next we need to define an int array to hold the color of all the pixels in the bitmap, but how do we know what color each pixel is? This time we need to traverse the Bitmatrix, if the point on the Bitmatrix indicates that the point has data, then the corresponding pixel on the bitmap is black, otherwise it is white. The return value of the Get method in Bitmatrix is a Boolean type, True indicates that the point has data, and False indicates that the point has no data. Through two nested for loops to iterate over the Bitmatrix, and then assign values to the pixels array, ok,pixels the array has values, then call Bitmap CreateBitmap method to create a bitmap, The CreateBitmap method receives a total of 6 parameters, the first parameter represents the color of all pixels in bitmap, the second parameter represents the pixel offset, the third parameter represents how many pixels bitmap each line, and the fourth parameter represents the width of the generated bitmap. The fifth parameter represents the height of the generated bitmap, and the sixth parameter represents the color mode of the generated bitmap, since the QR code is only available in black and white, so we can use the rgb_565 directly without considering the transparency. OK, so we get a picture of the QR code, and finally we'll take a look at the Click event:

    public void generate (view view) {        Bitmap qrbitmap = Generatebitmap ("http://www.csdn.net", +/-);        Iv.setimagebitmap (Qrbitmap);    }

As follows:


1.3 Add logo to QR Code Center

OK, if you do not have special needs so this is OK, but we see most of the two-dimensional code of the center has a logo, then how to achieve this effect? Here is the picture of the content, I encapsulated a method specifically to solve the problem, the code is as follows:

    Private Bitmap Addlogo (Bitmap qrbitmap, Bitmap logobitmap) {int qrbitmapwidth = Qrbitmap.getwidth ();        int qrbitmapheight = Qrbitmap.getheight ();        int logobitmapwidth = Logobitmap.getwidth ();        int logobitmapheight = Logobitmap.getheight ();        Bitmap Blankbitmap = Bitmap.createbitmap (Qrbitmapwidth, Qrbitmapheight, Bitmap.Config.ARGB_8888);        Canvas canvas = new canvas (BLANKBITMAP);        Canvas.drawbitmap (qrbitmap, 0, 0, NULL);        Canvas.save (Canvas.all_save_flag);        float scalesize = 1.0f; while (logobitmapwidth/scalesize) > (QRBITMAPWIDTH/5) | |        (logobitmapheight/scalesize) > (QRBITMAPHEIGHT/5) {scalesize *= 2;        } float SX = 1.0f/scalesize;        Canvas.scale (SX, SX, QRBITMAPWIDTH/2, QRBITMAPHEIGHT/2);        Canvas.drawbitmap (Logobitmap, (qrbitmapwidth-logobitmapwidth)/2, (Qrbitmapheight-logobitmapheight)/2, NULL);        Canvas.restore ();    return blankbitmap; }

Addlogo This method receives two parameters, The first parameter is the bitmap image of the two-dimensional code we generated in section 1.2, the second parameter is our logo image, in which I first get two bitmap of the respective width, then create a new blank bitmap, this new blank bitmap the width of the high and the width of the two-dimensional code of the uniform, and then create a A Canvas object, when you create a canvas object, the Blankbitmap is passed in, so that what I draw is the equivalent of drawing on the Blankbitmap. The Drawbitmap method of the canvas receives four parameters, the first is the bitmap object you want to draw, the second and third are the coordinates of the upper-left corner of the bitmap that you want to draw, the fourth parameter is a brush, and generally we give a null to it, If you want to set the repetition pattern and so on the effect can not give null. We use the Drawbitmap method to draw the original two-dimensional code image, after the drawing is completed, call the canvas save method, save the current drawing state, and then zoom the canvas, reduce the canvas after we draw the logo, A bunch of cases the width of the logo for the two-dimensional code of the original width of 1/5 (center logo image should not be too large, otherwise it will affect the identification of two-dimensional code), so we first through a while loop to get the scale, and then call the canvas scale method to zoom the canvas, The first two parameters represent a wide-height scale, greater than 1 means magnification, less than 1 means shrinking, and the latter two represent the center point of scaling. After the zoom is complete, we can draw the logo, after the logo is drawn, call the canvas's Restore method to restore the canvas to its original state, and finally return the Blankbitmap. Call this method in the Click event, the code is as follows:

    public void generate (view view) {        Bitmap qrbitmap = Generatebitmap ("http://www.csdn.net", +/-);        Bitmap Logobitmap = Bitmapfactory.decoderesource (Getresources (), r.mipmap.ic_launcher);        Bitmap Bitmap = Addlogo (Qrbitmap, logobitmap);        Iv.setimagebitmap (bitmap);    }

As follows:

OK, at this point, our two-dimensional code generation is finished, it is so simple.

2. Identification of two-dimensional code

Two-dimensional code recognition is a slightly troublesome thing, in general, we directly use the Open source project zxing on GitHub, the project is completed on the basis of our previous core package (). Of course, if you need to define the relevant pages yourself and so on, we'll talk about that later. Let's take a look at how to bring the open source project on GitHub to our project.

Import project We are mainly divided into the following several steps:

1. Create a new project named Qrreader (this step is not required and can be based on your project needs)

2. Download the Zxing Project

3. Create a new module in the new project and select the Android Library during the creation process, such as:

4. Open our project in the folder, find the library created in the third step, merge the Android and Android-core two folders from the Zxing project in the second step to the library, for example:


There are several project files in the Android folder which are mainly merged as follows:

Once the merge is complete, copy the core jar packages we downloaded earlier into our library's Libs folder, and then we'll take a look at our library:

5. Refer to this module in our project and compile the project.

6. The project will be error after compiling, this time we need to change all the switch statements in the library to If...else if ... else if.

7. After completion of the 6th step will be error, this time we need to the library's manifest file in the Application node's Icon property is deleted, and then compile there is no problem.

OK, after the 7 steps above this open source project was successfully introduced into our own project, in this open source project, there is a captureactivity, this activity is specifically used to scan the QR code, So we just have to start this activity directly in our own project, and since Captureactivity is the startup item by default, we're going to remove captureactivity as the startup item in the Library's manifest file.

OK, now I have a button in my project, click this button I can scan QR code, the code is as follows:

    public void Go (view view) {        startactivity (new Intent (this, captureactivity.class));    }

OK, at this point, a simple QR code scan is complete, we have wood has felt very troublesome ah? Trouble is this time, because I use zxing as the library when the system will automatically generate an AAR package, with this AAR package, the future development will become very simple, then where is the AAR package? Such as:

Corresponding folder path everyone to find, with this AAR package, if I need to use the QR code scanning function, only need the following several simple steps:

1. Create a project

2. Create the module and select Import when you create the module. jar/. AAR package, then select just the AAR pack

3. Refer to this module in my app.



Finally, I have made my own AAR package available to you and can be used directly in the project, very convenient, but it is recommended that you try to generate an AAR package, the whole process is very interesting.


Zxinglibrary-release.aar Download


Above.


Playing the QR code generation and recognition of Android

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.