Java Two-dimensional code development

Source: Internet
Author: User

Previously wrote a lot about the two-dimensional code of things, has not had time to tidy up, so today first to introduce how to use Java to develop QR code. Generate two-dimensional code there are many jar packages can be implemented, such as Zxing,qrcode, the former is Google, the latter of Japan, here I will be two ways to do a simple introduction to the implementation of the method.

One, two-dimensional code principle

The two-dimensional barcode was first invented in Japan, it is to use a certain geometry according to a certain pattern in the plane (two-dimensional direction) distribution of black and white graphics data symbol information, in the code to skillfully use the composition of the computer's internal logic based on the "0", "1" bit stream concept, A number of geometric shapes corresponding to the binary are used to represent the literal numerical information, which is automatically read by the image input device or photoelectric scanning device to realize automatic information processing.

Second, the concrete realization

1.QRCode

(1). Get Qrcode.jar, download link:http://download.csdn.net/detail/xch_yang/9514836

(2). Add the jar package to the project's build path (copy the jar package to the project, right-click: Build path-Add to build path).

The code is as follows :

import java.awt.color;import java.awt.graphics2d;import java.awt.image.bufferedimage;import java.io.File; Import Java.io.ioexception;import Java.io.unsupportedencodingexception;import Javax.imageio.imageio;import Com.swetake.util.Qrcode; Public classqrcodeimg {/** * Generate QR Code image * @author Yang * @param content QR Code contents * @param save path of imgpath QR code image*/     Public Static voidgetqrcodeimg (String content,string imgpath) {intWidth= $; intheight= $; //Instantiate QRCodeQRCode qrcode=NewQRCode (); //set the error rate of the QR Code L (7%) M (15%) Q (25%) H (35%)Qrcode.setqrcodeerrorcorrect ('M'); Qrcode.setqrcodeencodemode ('B'); //set the QR code size (1~49)Qrcode.setqrcodeversion (7); //Set Picture sizeBufferedImage bufimg=Newbufferedimage (width, height, bufferedimage.type_int_bgr); //drawing two-dimensional code imagesGraphics2D gs=Bufimg.creategraphics (); //set the background color of the two-dimensional codeGs.setbackground (Color.White); //Create a rectangular areaGs.clearrect (0,0, width, height); //set the picture color value of the QR Code blackGs.setcolor (Color.Black); //gets a byte array of content, sets the encoding set        Try {            byte[] Contentbytes=content.getbytes ("Utf-8"); intpixoff=2; //output Two-dimensional code            if(contentbytes.length>0&&contentBytes.length< -) {boolean[][] codeout=Qrcode.calqrcode (contentbytes);  for(intI=0; i<codeout.length;i++){                     for(intj=0; j<codeout.length;j++){                        if(Codeout[j][i]) {Gs.fillrect (J*3+pixoff, i*3+pixoff,3,3);            }}}} gs.dispose ();            Bufimg.flush (); //generate two-dimensional code imagesFile imgfile=NewFile (Imgpath); Imageio.write (bufimg,"PNG", Imgfile); System. out. println ("Two-dimensional code generation success! "); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }     Public Static voidMain (string[] args) {getqrcodeimg ("http://m.55bbs.com/liren_2003609/","E:\\test.png"); }}

Result: The content is the link of the webpage picture, so after scanning the result, of course, you can change the content to text.

2.ZXing

(1). Get zxing Package, download link: http://download.csdn.net/detail/xch_yang/9514956

(2) Here we only need to zxing the Core-3.0.0.jar in the package, so add Core-3.0.0.jar to the build path.

Implementation code:

Create class: Imagewrite (the generation of QR codes requires this class)

Import Javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; Import Java.awt.image.BufferedImage;  PublicFinalclassImagewrite {Private StaticFinalintBLACK =0xff000000; Private StaticFinalintWhite =0xFFFFFFFF; PrivateImagewrite () {} Public Staticbufferedimage tobufferedimage (Bitmatrix matrix) {intwidth =matrix.getwidth (); intHeight =matrix.getheight (); BufferedImage Image=Newbufferedimage (width, height, bufferedimage.type_int_rgb);  for(intx =0; x < width; X + +) {              for(inty =0; Y < height; y++{Image.setrgb (x, y, matrix).Get(x, y)?black:white); }           }         returnimage; }           Public Static voidWriteToFile (Bitmatrix matrix, String format, file file) throws IOException {bufferedimage image=tobufferedimage (matrix); if(!imageio.write (image, format, file)) {                Throw NewIOException ("Could not write an image of format"+ Format +" to"+file); }      }          Public Static voidWriteToStream (Bitmatrix matrix, String format, OutputStream stream) throws IOException {bufferedimage image /c12>=tobufferedimage (matrix); if(!imageio.write (image, format, stream)) {                  Throw NewIOException ("Could not write an image of format"+format); }       }  }

Create class: Qrcodeencode

import java.io.file;import java.io.ioexception;import java.util.hashmap;import Java.util.map;import Com.google.zxing.barcodeformat;import Com.google.zxing.encodehinttype;import Com.google.zxing.MultiFormatWriter; Import Com.google.zxing.writerexception;import Com.google.zxing.common.BitMatrix; Public classQrcodeencode { Public Static voidMain (string[] args) {Try {            //Two-dimensional code contentString content ="Hello qrcode!"; //Two-dimensional code generation pathString Path ="F:/java Workspace"; Multiformatwriter Multiformatwriter=NewMultiformatwriter (); Map hints=NewHashMap (); Hints.put (Encodehinttype.character_set,"UTF-8"); Bitmatrix Bitmatrix= Multiformatwriter.encode (content, Barcodeformat.qr_code, -, -, hints); File file1=NewFile (Path,"test.jpg"); Imagewrite.writetofile (Bitmatrix,"jpg", file1); System. out. println ("Two-dimensional code has been generated! "); } Catch(IOException e) {e.printstacktrace (); } Catch(writerexception e) {e.printstacktrace (); }     }}

Result: QR code picture location: F:/java workspace/test.jpg Scan content: Hello qrcode!

here is a simple introduction of the use of Java to develop two-dimensional code, of course, you can also add a logo to the two-dimensional code, the implementation of the following introduction.

Java Two-dimensional code development

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.