Android: use zxing to generate QR code (support for logo design)

Source: Internet
Author: User
Tags save file
<span id="Label3"></p><p><p>Zxing is an open source repository for Google. can be used to generate two-dimensional code, scan two-dimensional code. The first part is described in this article.</p></p><p><p></p></p><p><p>First Up:</p></p><p><p><br></p></p><p><p>Zxing related various documents Official: https://github.com/zxing/zxing/releases</p></p><p><p>or download it here (only the jar package for this project, version: 3.2.0): link: Http://pan.baidu.com/s/1hq3s5EW Password:mvg7</p></p><p><p>1. Tool class for generating QR code</p></p><p><p></p></p><pre code_snippet_id="682952" snippet_file_name="blog_20150603_1_7656571" name="code" class="java">/** * QR code generation tool Class */public class Qrcodeutil {/** * generate QR Code bitmap * * @param content contents * @param widthpix Picture width * @param heightpix picture Height * @param logo icon in center of LOGOBM QR code (nullable) * @param filePath file path for storing QR code images * @return generate QR Code and save file successfully */public static Boolean createqrimage (String content, int widthpix, int heightpix, Bitmap logobm, String FilePath) {try {if (content = = NULL | | ". equals (content)) {return false; }//configuration parameters map<encodehinttype, object> hints = new hashmap<> (); Hints.put (encodehinttype.character_set, "utf-8"); Fault tolerance level hints.put (encodehinttype.error_correction, ErrorCorrectionLevel.H); Sets the width of the margin of Padding//hints.put (encodehinttype.margin, 2); Default is 4//image data conversion, using matrix conversion Bitmatrix Bitmatrix = new Qrcodewriter (). encode (content, barcodefor Mat. qr_code, widthpix, heightpix, hints); int[] pixels = new Int[widthpix * heightpix]; Here according to the two-dimensional code algorithm, generate a two-dimensional code image,///two for loop is the result of the picture Heng Lie scan for (int y = 0; y < heightpix; y++) { For (int x = 0; x < widthpix; + +) {if (bitmatrix.get (x, y)) {pixels[y * Widthpix + x] = 0xff000000; } else {pixels[y * Widthpix + x] = 0xffffffff; }}}//generate QR code picture format, use argb_8888 Bitmap Bitmap = Bitmap.createbitmap (widthp ix, heightpix, Bitmap.Config.ARGB_8888); Bitmap.setpixels (pixels, 0, widthpix, 0, 0, widthpix, heightpix); If (logobm! = Null) {bitmap = Addlogo (bitmap, logobm); }//you must use the Compress method to save the bitmap to a file for Reading. The direct return of the bitmap is no matter what the Compression. Memory Consumption is Huge. return bitmap! = null && bitmap.compress (Bitmap.CompressFormat.JPEG, new FileOutputStream (filePath)); } catch (Writerexception | IOException E) {e.printstacktrace (); } return false; }/** * Add logo to the middle of the QR code */private static Bitmap Addlogo (Bitmap src, Bitmap logo) {if (src = = Null) { Return null; } if (logo = = Null) {return src; }//get picture of the width of the high int srcwidth = Src.getwidth (); int srcheight = Src.getheight (); int logowidth = Logo.getwidth (); int logoheight = Logo.getheight (); If (srcwidth = = 0 | | srcheight = = 0) {return null; } if (logowidth = = 0 | | logoheight = = 0) {return src; The//logo size is 1/5 float scalefactor = srcwidth * 1.0f/5/logowidth for the overall size of the QR code; Bitmap Bitmap = Bitmap.createbitmap (srcwidth, srcheight, Bitmap.Config.ARGB_8888); Try {canvas canvas = new Canvas (bitmap); Canvas.drawbitmap (src, 0, 0, null); Canvas.scale (scalefactor, scalefactor, srcwidth/2, srcheight/2); Canvas.drawbitmap (logo, (srcwidth-logowidth)/2, (srcheight-logoheight)/2, null); Canvas.save (canvas.all_save_flag); Canvas.restore (); } catch (Exception E) {bitmap = null; E.getstacktrace (); } return bitmap; }}</pre>2. Use in Activity:<p><p></p></p><p><p></p></p><pre code_snippet_id="682952" snippet_file_name="blog_20150603_2_1950350" name="code" class="java">/** * QR code generation */public class Mainactivity extends actionbaractivity {@Override protected void onCreate (Bundle Savedin Stancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); Content final EditText contentet = (EditText) Findviewbyid (r.id.create_qr_content); Display two-dimensional code picture final ImageView ImageView = (ImageView) Findviewbyid (r.id.create_qr_iv); Whether to join the logo final CheckBox ADDLOGOCB = (CheckBox) Findviewbyid (r.id.create_qr_addlogo); Button createqrbtn = (button) Findviewbyid (r.id.create_qr_btn); Createqrbtn.setonclicklistener (new view.onclicklistener () {@Override public void OnClick (View V) { Final String FilePath = getfileroot (mainactivity.this) + file.separator + "qr_" + Sy Stem.currenttimemillis () + ". jpg"; When the QR code picture is large, the time it takes to generate the picture and save the file may be longer, so the new thread (new Runnable () {@Override public void Run () {boolean success = Qrcodeutil.createqrimage (contentet.gettex T (). toString (). trim (), addlogocb.ischecked ()?<p><p></p></p><p><p>Bitmapfactory.decoderesource (getresources (), r.mipmap.qr_logo): null, filePath); If (success) {runonuithread (new Runnable () {@Ov Erride public void Run () {imageview.setimagebitmap (bitm Apfactory.decodefile (filePath)); } }); }}). Start (); } }); }//file Store root folder private String getfileroot (context context) {if (environment.getexternalstoragestate (). equals (E Nvironment. MEDIA_MOUNTED)) {File external = Context.getexternalfilesdir (null); If (external! = Null) {return external.getabsolutepath (); }} return context.getfilesdir (). getabsolutepath (); }}</p></p></pre><p><p>3. The picture file in this project is saved in</p></p><p><p></p></p><pre code_snippet_id="682952" snippet_file_name="blog_20150603_3_5691184" name="code" class="java"><pre code_snippet_id="682952" snippet_file_name="blog_20150603_3_5691184" name="code" class="java">Context.getexternalfilesdir (null)</pre></pre>folder under The.<p><p></p></p><p><p>According to the official API document, from KitKat (Android 4.4), Save the file to this folder will not require the SD card read and write Permissions. however, after testing that the red rice Note and Meizu MX3 (the system is Android 4.4.4), does not require permission, but on my Huawei P6 (Android 4.4.2), must declare the ability to successfully save the File. That is, you must include the following in the manifest, for example:</p></p><p><p></p></p><pre code_snippet_id="682952" snippet_file_name="blog_20150603_4_8944340" name="code" class="java"><pre code_snippet_id="682952" snippet_file_name="blog_20150603_4_8944340" name="code" class="java"><uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android: Name= "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/></pre></pre>therefore, individual Pushes. The so-called don't need permission to start from Android 4.4.4.<br><br><br><p><p></p></p><p><p></p></p><p><p><br><br></p></p><p><p><br></p></p> <p><p>Android: use zxing to generate QR code (support for logo design)</p></p></span>

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.