Scan (generate) Two-dimensional Code demo (reprint)

Source: Internet
Author: User

Google offers a zxing open source project, which provides QR code and barcode scanning. Scan Barcode is directly read the contents of the barcode, scanning QR code is in accordance with their own designated QR Code format for encoding and decoding.

can go to http://code.google.com/p/zxing/download zxing project source code, and then according to the official document development, I use the zxing here is a simplified version, removed some general use unnecessary files, project works as follows:

One of the encoding package is I add on its basis, the function is based on the incoming string to generate a two-dimensional code image, return a bitmap, the rest of the package is Zxing project comes with. In addition to the layout of the scanning interface I have also modified, the official scanning interface is horizontal, I changed to vertical, and added the Top tab and Cancel button (Camera.xml), also need some files are colors.xml, Ids.xml, these are the original Zxing project, the last is libs the following jar package.

Let's take a look at the final effect:

The first is to generate a two-dimensional code based on the input string image (left), and then scan the QR code image can be displayed on the interface scan results (right):

Click on the Open Camera button to open the Scan box (left), scan the barcode results as follows (right):

Next look at how to use, the first is to copy some of the files in the Zxing project to our own project, and then configure the 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 for 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: Colo R/white "android:orientation=" vertical "> <button android:id=" @+id/btn_scan_barcode "Android:lay Out_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" > <textvi EW android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:textcolor= "@andro         Id: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_margin top= "30DP" android:hint= "Input the text"/> <button android:id= "@+id/btn_add_qrcode" Android        Oid: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_h eight= "Wrap_content" android:layout_margintop= "10DP" android:layout_gravity= "center"/&GT;&LT;/LINEARLAYOUT&G T

The following is the main activity code, the main function is to open the scan box, display scan results, based on the input string to generate a two-dimensional code image:

public class Barcodetestactivity extends activity {/** Called when the activity is first created. */private TextView R    Esulttextview;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);        Qrstredittext = (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 Scan Interface Scan 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 two-dimensional code images from a string and display them on the interface, The second parameter is the size of the picture (350*350) Bitmap qrcodebitmap = Encodinghandler.createqrcode (contentstring, 350); Qrimgimageview.setimagebitmap (QRCODEBITMAP);} else {toast.maketext (barcodetestactivity.this, "Text can not is 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);//processing the scan result (shown on the interface) if (ResultCode = = RESULT_OK) {Bundle bundle = Data.getextras (); String Scanresult = bundle.getstring ("result"); Resulttextview.settext (Scanresult);}}


The code that generates the QR code image is in Encodinghandler.java:

Public final class Encodinghandler {private static final int BLACK = 0xff000000;public static Bitmap Createqrcode (String s Tr,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 < he ight; y++) {for (int x = 0; x < width; + +) {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, where to decode the results of the scan, enter Captureactivity.java to find the following method to operate on their own results:

/** * Handler Scan result * @param result * @param barcode */public void Handledecode (result result, Bitmap barcode) {Inac Tivitytimer.onactivity ();p laybeepsoundandvibrate (); 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 ();}


The above process does not take each step of the detailed steps to write, the overall idea is basically as above, the source download: http://download.csdn.net/detail/tangren03/4477631

Welcome to follow my Sina Weibo and I exchange: @ Tang Yu _ryan


Transferred from: http://blog.csdn.net/tangren03/article/details/7831826

Scan (generate) Two-dimensional Code demo (reprint)

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.