Android zxing QR code and barcode scanning

Source: Internet
Author: User

Recently, the company's Android project needs to use cameras for barcode or QR code scanning. Google to find an open-source
Zxing project. It provides scanning of QR codes and bar codes. Scanning a barcode is to directly read the content of the barcode. Scanning a QR code is encoded and decoded according to the specified QR code format.

1. What are QR code and barcode?

Two-dimensional Barcode was first invented in Japan. It records the data symbol information with a certain black and white pattern distributed on a plane (two-dimensional direction) according to a certain law, the concept of "0" and "1" bit streams that constitute the internal logic of computers is cleverly used in code compilation, A number of ry corresponding to the binary are used to represent the numerical value of the text. The input device of the image or the photoelectric scanning device can automatically read and read the text for automatic information processing. It has some commonalities of bar code technology: each code system has its specific character set, each character occupies a certain width, and has a certain verification function. At the same time, it also has the ability to automatically identify different rows of information, and to handle graphics rotation changes and other features.

Barcode is a graphical identifier used to express a set of information by arranging multiple black bars and white spaces in different widths according to certain encoding rules. A common bar code is a parallel line pattern formed by black bars (short bars) and white bars (empty bars) with a large difference in reflectivity. A bar code can mark the producing country, manufacturer, product name, production date, library classification number, email start and end location, category, date, and many other information of an item, therefore, it has been widely used in commodity circulation, book management, postal management, banking systems, and many other fields.

2. Introduction to zxing

Zxing is an open source Java class library used to parse various formats of bar code and QR code.

The latest version supports the following encoding formats:

  • UPC-A and UPC-E
  • EAN-8 and EAN-13
  • Code 39
  • Code 93
  • Code 128
  • QR code
  • ITF
  • Codabar
  • RSS-14 (all variants)
  • Data Matrix
  • PDF 417 ('alpha' quality)
  • Aztec ('alpha' quality)

At the same time, the official website provides Android, CPP, C #, iPhone, j2se, j2se, jruby, objc, RIM, Symbian and other application class libraries. For details, refer to the downloaded source code package.

3. Android encoding demonstration

The zxing used here is a simplified version, removing unnecessary files. The project and effects are as follows:

The encoding package is added on the original basis. The function is to generate a QR code Image Based on the input string and return a bitmap. Other packages are included in the zxing project. In addition, the layout of the scan interface is also modified. The official scan interface is horizontal. I changed it to vertical, and added the tab and cancel button (camera. XML), in addition, some files are colors. XML, IDs. XML, these are self-contained in the original zxing project, and finally the jar package under libs.

Next, let's take a look at how to use it. First, copy some files in the zxing project to our own project, and then Configure permissions in the mainifest file:

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

There is also the configuration of the scan interface activity:

   <activity            android:configChanges="orientation|keyboardHidden"            android:name="com.zxing.activity.CaptureActivity"            android:screenOrientation="portrait"            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"            android:windowSoftInputMode="stateAlwaysHidden" >   </activity>

Next is the layout file of my own project:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@android:color/white"    android:orientation="vertical" >    <Button        android:id="@+id/btn_scan_barcode"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="30dp"        android:text="Open camera" />        <LinearLayout         android:orientation="horizontal"        android:layout_marginTop="10dp"        android:layout_width="fill_parent"        android:layout_height="wrap_content">                <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textColor="@android:color/black"        android:textSize="18sp"        android:text="Scan result:" />                <TextView         android:id="@+id/tv_scan_result"       android:layout_width="fill_parent"       android:textSize="18sp"       android:textColor="@android:color/black"        android:layout_height="wrap_content" />    </LinearLayout>        <EditText         android:id="@+id/et_qr_string"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="30dp"        android:hint="Input the text"/>        <Button        android:id="@+id/btn_add_qrcode"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Generate QRcode" />        <ImageView         android:id="@+id/iv_qr_image"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:layout_gravity="center"/></LinearLayout>

The following is the main activity code. The main function is to open the scan box, display the scan results, and generate a QR code Image Based on the input string:

Public class barcodetestactivity extends activity {/** called when the activity is first created. */private textview resulttextview; private edittext qrstredittext; private imageview qrimgimageview; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); resulttextview = (textview) This. findviewbyid (R. id. TV _scan_result); qrstredi Ttext = (edittext) This. findviewbyid (R. id. et_qr_string); qrimgimageview = (imageview) This. findviewbyid (R. id. iv_qr_image); button scanbarcodebutton = (button) This. findviewbyid (R. id. btn_scan_barcode); scanbarcodebutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {// open the scan interface to scan the barcode or QR code intent opencameraintent = new intent (barcodetestactivity. this, captureactivity. class); Startactivityforresult (opencameraintent, 0) ;}}); button generateqrcodebutton = (button) This. findviewbyid (R. id. btn_add_qrcode); generateqrcodebutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {try {string contentstring = qrstredittext. gettext (). tostring (); If (! Contentstring. equals ("") {// generate a QR code Image Based on the string and display it on the interface. The second parameter is the image size (350*350) bitmap qrcodebitmap = encodinghandler. createqrcode (contentstring, 350); qrimgimageview. setimagebitmap (qrcodebitmap);} else {toast. maketext (barcodetestactivity. this, "text can not be empty", toast. length_short ). show () ;}} catch (writerexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}) ;}@ overrideprotected void onactivityresult (INT requestcode, int resultcode, intent data) {super. onactivityresult (requestcode, resultcode, data); // process the scan result (displayed on the Interface) if (resultcode = result_ OK) {bundle = data. getextras (); string scanresult = bundle. getstring ("result"); resulttextview. settext (scanresult );}}}

The code for generating the QR code is in encodinghandler. Java:

public final class EncodingHandler {private static final int BLACK = 0xff000000;public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();          hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix matrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);int width = matrix.getWidth();int height = matrix.getHeight();int[] pixels = new int[width * height];for (int y = 0; y < height; y++) {for (int x = 0; x < width; x++) {if (matrix.get(x, y)) {pixels[y * width + x] = BLACK;}}}Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);bitmap.setPixels(pixels, 0, width, 0, 0, width, height);return bitmap;}}

Finally, go to captureactivity. Java and find the following method to perform operations on the scan results:

  /** * Handler scan result * @param result * @param barcode */public void handleDecode(Result result, Bitmap barcode) {inactivityTimer.onActivity();playBeepSoundAndVibrate();String resultString = result.getText();//FIXMEif (resultString.equals("")) {Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();}else {//System.out.println("Result:"+resultString);Intent resultIntent = new Intent();Bundle bundle = new Bundle();bundle.putString("result", resultString);resultIntent.putExtras(bundle);this.setResult(RESULT_OK, resultIntent);}CaptureActivity.this.finish();}
4. Java-side encoding demonstration

Code (EAN-13) and QR code (qrcode) coding and decoding examples, for your reference, using the source code core and javase below the relevant source code, the attachment provides the self-compiled lib package:

  • Zxing. Jar
  • Zxing-j2se.jar

    For applications related to various mobile phone systems, if you are interested, you can download the official source code package, which contains detailed application descriptions.

    1) demonstration of QR code encoding and decoding:

    Encoding example:

    Package Michael. zxing; import Java. io. file; import Java. util. hashtable; import COM. google. zxing. barcodeformat; import COM. google. zxing. encodehinttype; import COM. google. zxing. multiformatwriter; import COM. google. zxing. client. j2se. matrixtoimagewriter; import COM. google. zxing. common. bitmatrix; import COM. google. zxing. qrcode. decoder. errorcorrectionlevel;/*** @ blog http://sjsky.iteye.com * @ author Michael */P Ublic class zxingencoderhandler {/*** encoding * @ Param Contents * @ Param width * @ Param height * @ Param imgpath */Public void encode (string contents, int width, int height, string imgpath) {hashtable <object, Object> hints = new hashtable <object, Object> (); // specify the error correction level hints. put (encodehinttype. error_correction, errorcorrectionlevel. l); // specify the hints encoding format. put (encodehinttype. character_set, "GBK"); try {Bi Tmatrix bitmatrix = new multiformatwriter (). encode (contents, barcodeformat. qr_code, width, height, hints); matrixtoimagewriter. writetofile (bitmatrix, "PNG", new file (imgpath);} catch (exception e) {e. printstacktrace () ;}/ *** @ Param ARGs */public static void main (string [] ARGs) {string imgpath = "D:/1.png "; string contents = "Hello word! "; Int width = 300, Height = 300; zxingencoderhandler handler = new zxingencoderhandler (); handler. encode (contents, width, height, imgpath );}}

    The QR code generated after running is shown as follows:

    Use the QR code scanning software on your mobile phone (Android quick Bi QR code used by myself) to test the recognition success as follows:

    Decoding example:

    Package Michael. zxing; import Java. AWT. image. bufferedimage; import Java. io. file; import Java. util. hashtable; import javax. imageIO. imageIO; import COM. google. zxing. binarybitmap; import COM. google. zxing. decodehinttype; import COM. google. zxing. luminancesource; import COM. google. zxing. multiformatreader; import COM. google. zxing. result; import COM. google. zxing. client. j2se. bufferedimageluminancesource; import COM. google. zxing. common. hybridbinarizer;/*** @ blog http://sjsky.iteye.com * @ author Michael */public class zxingdecoderhandler {/*** @ Param imgpath * @ return string */Public String decode (string imgpath) {bufferedimage image = NULL; Result result = NULL; try {image = ImageIO. read (new file (imgpath); If (image = NULL) {system. out. println ("the decode image may not exit. ");} luminancesource source = new bufferedimageluminancesource (image); binarybitmap bitmap = new binarybitmap (New hybridbinarizer (source); hashtable <object, Object> hints = new hashtable <object, object> (); hints. put (decodehinttype. character_set, "UTF-8"); Result = new multiformatreader (). decode (bitmap, hints); return result. gettext ();} catch (exception e) {e. printstacktrace ();} return NULL;}/*** @ Param ARGs */public static void main (string [] ARGs) {string imgpath = "D:/1.png "; zxingdecoderhandler handler = new zxingdecoderhandler (); string decodecontent = handler. decode (imgpath); system. out. println ("decoded content:"); system. out. println (decodecontent );}}

    The decoded content is as follows:
    Hello word!

    2) barcode (EAN-13) encoding and decoding Demo:

    Encoding example:

    Package Michael. zxing; import Java. io. file; import COM. google. zxing. barcodeformat; import COM. google. zxing. multiformatwriter; import COM. google. zxing. client. j2se. matrixtoimagewriter; import COM. google. zxing. common. bitmatrix; /*** @ blog http://sjsky.iteye.com * @ author Michael */public class zxingean13encoderhandler {/*** encoding * @ Param Contents * @ Param width * @ Param height * @ Param imgpath */ public void encode (string contents, int width, int height, string imgpath) {int codewidth = 3 + // start Guard (7*6) + // left bars 5 + // middle guard (7*6) + // right bars 3; // end guard codewidth = math. max (codewidth, width); try {bitmatrix = new multiformatwriter (). encode (contents, barcodeformat. ean_13, codewidth, height, null); matrixtoimagewriter. writetofile (bitmatrix, "PNG", new file (imgpath);} catch (exception e) {e. printstacktrace () ;}/ *** @ Param ARGs */public static void main (string [] ARGs) {string imgpath = "D:/2.png "; // Yida sugar-free chewing gum barcode string contents = "6923450657713"; int width = 105, Height = 50; zxingean13encoderhandler handler = new zxingean13encoderhandler (); handler. encode (contents, width, height, imgpath );}}

    The generated barcode image is as follows:

    Use the barcode scanning software of your mobile phone (I used the android quick Bi QR code) to test the recognition success as follows:

    Decoding example:

    Package Michael. zxing; import Java. AWT. image. bufferedimage; import Java. io. file; import javax. imageIO. imageIO; import COM. google. zxing. binarybitmap; import COM. google. zxing. luminancesource; import COM. google. zxing. multiformatreader; import COM. google. zxing. result; import COM. google. zxing. client. j2se. bufferedimageluminancesource; import COM. google. zxing. common. hybridbinarizer;/*** @ blog http://sjsky.iteye.com * @ author Michael */public class zxingean13decoderhandler {/*** @ Param imgpath * @ return string */Public String decode (string imgpath) {bufferedimage image = NULL; Result result = NULL; try {image = ImageIO. read (new file (imgpath); If (image = NULL) {system. out. println ("the decode image may not exit. ");} luminancesource source = new bufferedimageluminancesource (image); binarybitmap bitmap = new binarybitmap (New hybridbinarizer (source); Result = new multiformatreader (). decode (bitmap, null); return result. gettext ();} catch (exception e) {e. printstacktrace ();} return NULL;}/*** @ Param ARGs */public static void main (string [] ARGs) {string imgpath = "D:/2.png "; zxingean13decoderhandler handler = new zxingean13decoderhandler (); string decodecontent = handler. decode (imgpath); system. out. println ("decoded content:"); system. out. println (decodecontent );}}

    The decoded content is as follows:
    6923450657713

    5. source code instructions and downloads

    Official example:

    Barcodebench (barcode release 4.31 for Android featured must install this APK before running the zxingtest Project)

    Zxingtest (Android client calls barcodebench test example)

    Simplified example:

    Barcodetest (simplified Android-side scanning and decoding example)

    Qrcode (Java side scan and decoding example)

    Source code download

     

    Reprint please indicate the source http://blog.csdn.net/shimiso
    Welcome to our technical exchange group: 173711587

  • 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.