Android-based zxing QR code generation and Identification

Source: Internet
Author: User

Android-based zxing QR code generation and Identification

QR code:

The data symbol information is recorded using a certain black/white image distributed on a plane (two-dimensional direction) according to a certain rule;

In code compilation, the concept of 0-bit and 1-bit streams that constitute the Logic Basis of the computer is cleverly used to represent the text numerical value information using several geometric shapes corresponding to the binary, automatic Information processing is achieved through automatic reading by image input devices or photoelectric scanning devices;

The QR code can express information both horizontally and vertically, so it can express a large amount of information in a small area;

The advantage of QR codes over bar codes is space saving;

 

Zxing introduction:

Zxing is an open-source code library for 1D/2D bar code Image Processing in multiple formats implemented in java. It contains interfaces associated with other languages.

Zxing can scan and decode the barcode and QR code using the built-in camera of the mobile phone.

Zxing can encode and decode barcode and QR code.

Zxing currently supports the following formats:

UPC-A, UPC-E

EAN-8, EAN-13

39 yards

93 yards

Code 128:

QR code

 

Use of zxing on Android:

The following two methods can be used:

1. Place the zxing jar package in the lib library of the project, and copy the corresponding class source code to the project. The entire folder is copied quickly;

2. Use the zxing project as the dependent database of the current project and use it directly;

 

 

You can use one instance to complete the following three functions:

1. Generate a QR code;

2. parse the QR code image;

3. Scan and parse the QR code;

 

The final result is as follows:

 

Before creating a new project, we must import the dependent library to Eclipse. The original project folder of the dependent library has been packaged and can be downloaded at the end of the article.

 

The QR code (Image Recognition) feature requires a class named RGBLuminanceSource. The content of this class is 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 (); // obtain the width and height of the image. int width = bitmap. getWidth (); int height = bitmap. getHeight (); // get the image Prime int [] pixels = new int [width * height]; // bitmap. getPixels (pixels, 0, width, 0, 0, width, height); // to measure the pure decoding speed, before the gray array of the entire image, this is the same channel // YUVLuminanceSource in practical applications. // Obtain the number of bytes in pixel size. luminances = new byte [width * height]; // obtain the pixel color of the image at each point. for (int y = 0; y 

Next, you should pay special attention to the configuration of manifest, which requires adding permissions and the declaration of an Activity in the dependent Library:

 

 

    
     
      
       
        
                             
       
        
       
                          
     
    
   
  
 

Well, now let's take a look at how the Activity class we have compiled implements the three functions mentioned 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 contentEditText = 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 the QR code image and encapsulate the returned results in the Result object private com. google. zxing. result parseQRcodeBitmap (String bitmapPath) {// parse the Conversion Type UTF-8Hashtable
 
  
Hints = new Hashtable
  
   
(); Hints. put (DecodeHintType. CHARACTER_SET, UTF-8); // obtain the image to be parsed BitmapFactory. options options = new BitmapFactory. options (); // if we set inJustDecodeBounds to true, BitmapFactory. decodeFile (String path, Options opt) // does not actually return a Bitmap to you. It only returns its width and height to options. inJustDecodeBounds = true; // bitmap is null at this time. After this code, options. outWidth and options. outHeight is the width and height of Bitmap bitmap = BitmapFactory. decodeFile (bitmapPath, options); // set the side length of the image we want to obtain (the QR code image is square) to 400 pixels/** options. outHeight = 400; options. outWidth = 400; options. inJustDecodeBounds = false; bitmap = BitmapFactory. decodeFile (bitmapPath, options); * // although bitmap is limited to the size we want, it does not save memory. If you want to save memory, we also need to use the inSimpleSize attribute options. inSampleSize = options. outHeight/400; if (options. inSampleSize <= 0) {options. inSampleSize = 1; // prevent the value from being less than or equal to 0}/*** auxiliary memory saving settings ** options. inPreferredConfig = Bitmap. config. ARGB_4444; // The default value is Bitmap. config. ARGB_8888 * options. inPurgeable = true; * options. ininputwritable able = true; */options. inJustDecodeBounds = false; bitmap = BitmapFactory. decodeFile (bitmapPath, options); // create an RGBLuminanceSource object and pass the bitmap image to this object. RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource (bitmap ); // convert the image to binary image BinaryBitmap binaryBitmap = new BinaryBitmap (new HybridBinarizer (rgbLuminanceSource); // initialize the resolution object QRCodeReader reader = new QRCodeReader (); // start parsing Result 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); if (cursor. moveToFirst () {int columnIndex = cursor. getColumnIndex (MediaStore. images. media. DATA); System. out. println (columnIndex); // obtain the absolute path of the selected QR code image. imgPath = cursor. getString (columnIndex);} cursor. close (); // get resolution Result ret = parseQRcodeBitmap (imgPath); Toast. makeText (MainActivity. this, resolution result: + ret. toString (), Toast. LENGTH_LONG ). show (); break; case PHOTO_PIC: String result = data. getExtras (). getString (result); Toast. makeText (MainActivity. this, resolution result: + result, Toast. LENGTH_LONG ). show (); break; default: break ;}}@ SuppressLint (InlinedApi) @ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. button1: // obtain the content String content = contentEditText. getText (). toString (); // determines whether the content is null. if (null = content |. equals (content) {Toast. makeText (MainActivity. this, enter the content of the QR code to be written ..., toast. LENGTH_SHORT ). show (); return;} try {// generate a QR code image. The first parameter is the content of the QR code, and the second parameter is the side length of the square image. The unit is pixel 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 page and select a QR code image Intent intent1 = new Intent (); // if (android. OS. build. VERSION. SDK_INT <19) {// 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 the QR code image); startActivityForResult (intent2, CHOOSE_PIC); break; case R. id. button3: // go to the image taking page and scan the QR code Intent intent3 = new Intent (MainActivity. this, CaptureActivity. class); startActivityForResult (intent3, PHOTO_PIC); break; default: break ;}}}
  
 

The link for packaging all the code is attached. If you need it, you can download it and import it to your Eclipse:

 

Android Zxing Demo

 

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.