Android QR code open source project zxing use case simplification and generation of QR code, barcode

Source: Internet
Author: User

On an article: Android QR code open source project Zxing compiled, compiled out after a test program: captureactivity more complex, I just want to remove some of the unused things, with the look more convenient, QR code and barcode of the epidemic since needless to say.

For example, the directory structure is as follows:


Modified program directory structure, removed a lot of features, if sharing, settings and so on.


First on


Scan the zxing generated barcode and QR code results



Scanning interface


Scan the barcode of a product


The entire program only modifies the following two classes, others are copied directly from the original demo


Code to generate a QR code

/** * Generate QR code to convert the address or string, can be Chinese * * @param URL * @param width * @param height * @return */public Bitmap createqrimage (string URL, final int width, final int height) {try {//To determine URL legitimacy if (url = = NULL | | ". Equals (URL) | | Url.length () < 1) {return null;} Hashtable<encodehinttype, string> hints = new Hashtable<encodehinttype, string> (); Hints.put ( Encodehinttype.character_set, "Utf-8");//image data conversion, using matrix conversion Bitmatrix Bitmatrix = new Qrcodewriter (). Encode (URL, Barcodeformat.qr_code, width, height, hints); int[] pixels = new Int[width * height];//here Follow the two-dimensional code of the algorithm, the generation of two-dimensional code image,//Two for loop Is the result of the picture Heng Lie scan for (int y = 0; y < height; y++) {for (int x = 0; x < width; x + +) {if (Bitmatrix.get (×, y)) {Pixels[y * WI DTH + x] = 0xff000000;} else {pixels[y * width + x] = 0xFFFFFFFF;}}} Generate two-dimensional code picture format, using Argb_8888bitmap bitmap = Bitmap.createbitmap (width, height,bitmap.config.argb_8888); Bitmap.setpixels (pixels, 0, width, 0, 0, width, height); return bitmap;} catch (Writerexception e) {e.printstacktrace ();} Return NULL;} 
Can generate Chinese


Generate barcode Key code, the following code is the barcode and barcode under the text merged into a picture display.

/** * Generate Barcodes * * @param context * @param contents * Content required to generate * @param desiredwidth * Generate barcodes for broadband * @para M Desiredheight * The height of the barcode generated * @param Displaycode * Whether the content is displayed below the barcode * @return */public static Bitmap Crea TBarcode (context context, String contents,int desiredwidth, int desiredheight, Boolean displaycode) {Bitmap Ruseltbitmap = null;/** * Blank width reserved at both ends of the picture */int MARGINW = 20;/** * Barcode encoding type */barcodeformat Barcodeformat = barcodeformat.code_128;if (di Splaycode) {Bitmap Barcodebitmap = encodeasbitmap (contents, barcodeformat,desiredwidth, desiredheight); Bitmap Codebitmap = creatcodebitmap (contents, Desiredwidth + marginw, desiredheight, context); Ruseltbitmap = Mixturebi TMap (Barcodebitmap, Codebitmap, New PointF (0, Desiredheight));} else {Ruseltbitmap = Encodeasbitmap (contents, barcodeformat,desiredwidth, desiredheight);} return ruseltbitmap;} /** * Generate Barcode Bitmap * * @param contents * Content required to generate * @param format * encoded format * @param desiredwidTH * @param desiredheight * @return * @throws writerexception */protected static Bitmap encodeasbitmap (String contents,bar Codeformat format, int desiredwidth, int desiredheight) {final int white = 0xffffffff;final int BLACK = 0xff000000; Multiformatwriter writer = new Multiformatwriter (); Bitmatrix result = Null;try {result = Writer.encode (contents, format, desiredwidth,desiredheight, null);} catch (Writerex Ception e) {//TODO auto-generated catch Blocke.printstacktrace ();} int width = result.getwidth (); int height = result.getheight (); int[] pixels = new Int[width * height];//All is 0, or Blac  K, by defaultfor (int y = 0; y < height; y++) {int offset = y * width;for (int x = 0; x < width, x + +) {Pixels[offset + x] = Result.get (x, y)? Black:white;}} Bitmap Bitmap = Bitmap.createbitmap (width, height,bitmap.config.argb_8888); Bitmap.setpixels (pixels, 0, width, 0, 0, width, height); return bitmap;} /** * Generate display encoded BITMAP * * @param contents * @param width * @param height * @param context *@return */protected static Bitmap creatcodebitmap (String contents, int width,int height, context context) {TextView TV = n EW TextView (context); Linearlayout.layoutparams layoutparams = new Linearlayout.layoutparams (layoutparams.match_parent, LayoutParams.WRAP _content); Tv.setlayoutparams (layoutparams); Tv.settext (contents); tv.setheight (height); Tv.setgravity ( Gravity.center_horizontal); tv.setwidth (width); tv.setdrawingcacheenabled (true); Tv.settextcolor (Color.BLACK); Tv.measure (Measurespec.makemeasurespec (0, measurespec.unspecified), Measurespec.makemeasurespec (0, measurespec.unspecified)); tv.layout (0, 0, tv.getmeasuredwidth (), Tv.getmeasuredheight ()); Tv.builddrawingcache (); Bitmap Bitmapcode = Tv.getdrawingcache (); return bitmapcode;} /** * Merge two bitmap into a single * * @param first * @param second * @param frompoint * The starting position of the second bitmap start drawing (relative to number one bitmap) *  @return */protected static Bitmap Mixturebitmap (Bitmap First, Bitmap second,pointf frompoint) {if (first = = NULL | | second = = NULL | | Frompoint= = null) {return null;} int marginw = 20; Bitmap Newbitmap = Bitmap.createbitmap (first.getwidth () + second.getwidth () + marginw,first.getheight () + Second.getheight (), config.argb_4444); Canvas CV = new canvas (newbitmap); Cv.drawbitmap (first, MARGINW, 0, NULL); Cv.drawbitmap (second, frompoint.x, Frompoint.y , null); Cv.save (Canvas.all_save_flag); Cv.restore (); return newbitmap;}
Captureactivity.java is the interface for scanning QR codes and barcodes, initializing the camera and opening scan threads

private void Initcamera (Surfaceholder surfaceholder) {if (Surfaceholder = = null) {throw new IllegalStateException ("No Sur Faceholder provided ");} if (Cameramanager.isopen ()) {zxingapplication.print_i ("captureactivity", "Initcamera () while already open--late Surfaceview callback? "); return;} try {cameramanager.opendriver (surfaceholder);} catch (IOException IoE) {return;} catch (RuntimeException e) {return;} if (handler = = null) {handler = new Captureactivityhandler (this, decodeformats,decodehints, CharacterSet, Cameramanager) ;} Zxingapplication.print_i ("Captureactivity", "Initcamera-----------Finish");}
The results of the scan are processed in the Captureactivityhandler.java class

@Overridepublic void handlemessage (Message message) {switch (message.what) {case R.id.restart_preview: Restartpreviewanddecode (); break;case r.id.decode_succeeded:state = state.success; Bundle bundle = Message.getdata (); Bitmap Barcode = Null;float Scalefactor = 1.0f;if (bundle! = null) {byte[] Compressedbitmap = Bundle.getbytearray (decodeth Read. BARCODE_BITMAP); if (compressedbitmap! = null) {BARCODE = Bitmapfactory.decodebytearray (compressedbitmap,0, Compressedbitmap.length, NULL);//Mutable Copy:barcode = Barcode.copy (Bitmap.Config.ARGB_8888, True);} Scalefactor = Bundle.getfloat (decodethread.barcode_scaled_factor);} Activity.handledecode (Result) message.obj, barcode, scalefactor); break;case r.id.decode_failed://We ' re decoding as Fast as possible, so when one decode fails,//start another.state = State.preview;cameramanager.requestpreviewframe (decod Ethread.gethandler (), r.id.decode); Break;case R.id.return_scan_result:activity.setresult (Activity.RESULT_OK, ( Intent) message.obj); Activity.finIsh (); break;case r.id.launch_product_query:string url = (String) message.obj;intent Intent = new Intent (intent.action_ VIEW); Intent.addflags (Intent.flag_activity_clear_when_task_reset); Intent.setdata (Uri.parse (URL)); ResolveInfo ResolveInfo = Activity.getpackagemanager (). Resolveactivity (Intent, packagemanager.match_default_only);  String browserpackagename = null;if (resolveInfo! = NULL && Resolveinfo.activityinfo! = null) {Browserpackagename = ResolveInfo.activityInfo.packageName; LOG.D (TAG, "Using browser in package" + Browserpackagename);} Needed for default Android browser/chrome only Apparentlyif ("Com.android.browser". Equals (browserpackagename) | | "Com.android.chrome". Equals (Browserpackagename)) {intent.setpackage (browserpackagename); Intent.addflags ( Intent.flag_activity_new_task); Intent.putextra (browser.extra_application_id,browserpackagename);} try {activity.startactivity (intent);} catch (Activitynotfoundexception ignored) {LOG.W (TAG, "Can ' t find anything to Handle VIEW of URI "+ URL);} Break;}}
In case r.id.decode_succeeded the branch will pass through Activity.handledecode (result) message.obj, barcode, scalefactor);

/** * A Valid barcode have been found, so give an indication of success and show * the results. * * @param Rawresult * The contents of the barcode.  * @param scalefactor * Amount by which thumbnail was scaled * @param barcode * A greyscale Bitmap of The camera data which was decoded. */public void Handledecode (Final Result rawresult, Bitmap barcode,float scalefactor) {inactivitytimer.onactivity ();// Resulthandler Resulthandler = Resulthandlerfactory.makeresulthandler (//this, Rawresult); Boolean fromlivescan = Barcode! = NULL; Alertdialog.builder dialog = new Alertdialog.builder (this), if (barcode = = null) {Dialog.seticon (null);} else {drawable Dr awable = new Bitmapdrawable (barcode);d Ialog.seticon (drawable);} Dialog.settitle ("Scan results");d Ialog.setmessage (Rawresult.gettext ());d Ialog.setnegativebutton ("OK", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {// Open the scanned address with the default browser intent intent = new intent (); Intent.sEtaction ("Android.intent.action.VIEW"); Uri Content_url = Uri.parse (Rawresult.gettext ()); Intent.setdata (Content_url); startactivity (intent); Finish ();}); Dialog.setpositivebutton ("Cancel", new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {finish ();}}); Dialog.create (). Show ();
Here just to show the results of the scan, can actually be based on different needs to deal with, if scan out QR code can be opened with HTTP, one thing to note, my ADT version is V23.0.2.1259578, need to run 4.0 of the system on

Example code: http://download.csdn.net/detail/deng0zhaotai/7696615


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.