Java uses zxing to generate/parse two-dimensional code images

Source: Internet
Author: User
Tags image processing library

Zxing is an open source multi-format 1d/2d barcode image Processing Library, implemented in Java. The point is to use the built-in camera on the phone to scan and decode the barcode on the device without communicating with the server. However, the project can also be used to encode and decode barcodes on desktops and servers. These formats are currently supported:

  • Upc-a and UPC-E
  • EAN-8 and EAN-13
  • Code 39
  • Code 93
  • Code 128
  • ITF
  • Codabar
  • RSS-14 (all variants)
  • RSS Expanded (most variants)
  • QR Code
  • Data Matrix
  • Aztec (' Beta ' quality)
  • PDF 417 (' alpha ' qua

Only use it here to generate/parse two-dimensional code: (parse QR code to add)

To create a MAVEN project, add a zxing jar dependency to the Pom.xml file:

    <!--Zxingqrcode Build support Package--    <!--https://Mvnrepository.com/artifact/com.google.zxing/core -    <dependency>        <groupId>com.google.zxing</groupId>        <artifactId> core</artifactid>        <version>3.3.3</version>    </dependency>    <!--https: // mvnrepository.com/artifact/com.google.zxing/javase--    <dependency>        <groupId>com.google.zxing</groupId>        <artifactid>javase</ artifactid>        <version>3.3.3</version>    </dependency>

The following is a consolidated QR code generation tool class:

 PackageCom.esheng.util;ImportJava.awt.AlphaComposite;ImportJava.awt.Color;ImportJava.awt.Graphics2D;ImportJava.awt.image.BufferedImage;ImportJava.io.File;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map;ImportJavax.imageio.ImageIO;ImportCom.google.zxing.BarcodeFormat;ImportCom.google.zxing.EncodeHintType;ImportCom.google.zxing.MultiFormatWriter;Importcom.google.zxing.WriterException;ImportCom.google.zxing.client.j2se.MatrixToImageConfig;ImportCom.google.zxing.client.j2se.MatrixToImageWriter;ImportCom.google.zxing.common.BitMatrix;ImportCom.google.zxing.common.CharacterSetECI;ImportCom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/*** QRCode Generation tool class *@author: Linwenli * @date: 2018-08-23 12:45:34*/ Public classQrcodeutils {/*** QR Code BufferedImage Object Generation method *@authorLinwenli * @date 2018-08-23 12:51:00 *@paramcontents Two-dimensional code content *@paramwidth Two-dimensional code picture breadth *@paramheight Two-dimensional code picture Heights *@parammargin Two-dimensional code border (0,2,4,8) *@throwsException *@return: BufferedImage*/     Public StaticBufferedImage Createqrcode (String contents,intWidthintHeightintMarginthrowsException {if(contents = =NULL|| Contents.equals ("")) {            Throw NewException ("Contents cannot be empty. "); }        //Two-dimensional code basic parameter settingMap<encodehinttype, object> hints =NewHashmap<>(); Hints.put (Encodehinttype.character_set, Characterseteci.utf8);//set encoding character set Utf-8Hints.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H);//set the error correction level l/m/q/h, the higher the error correction level, the more difficult to identify, the current set to the highest level of HHints.put (Encodehinttype.margin, MARGIN);//can be set to a range of 0-10, but only four changes 0 1 (2) 3 (4 5 6) 7 ( 8 9)//Create a picture of type QRCodeBarcodeformat format =Barcodeformat.qr_code; //creating a bit matrix objectBitmatrix matrix =NULL; Try {            //generating a bit matrix object corresponding to the QR codeMatrix =NewMultiformatwriter (). Encode (contents, format, width, height, hints); } Catch(writerexception e) {e.printstacktrace (); }        //set the parameters of a bit matrix to a pictureMatrixtoimageconfig config =NewMatrixtoimageconfig (Color.black.getRGB (), Color.white.getRGB ()); //bit matrix objects go to BufferedImage objectsBufferedImage QRCode =matrixtoimagewriter.tobufferedimage (Matrix, config); returnQRCode; }        /*** QR code add logo *@authorLinwenli * @date 2018-08-23 13:17:07 *@paramQRCode *@paramwidth Two-dimensional code picture breadth *@paramheight Two-dimensional code picture Heights *@paramlogopath Icon Logo path *@paramlogosizemultiple Two-dimensional code and logo size ratio *@throwsException *@return: BufferedImage*/     Public StaticBufferedImage Createqrcodewithlogo (BufferedImage QRCode,intWidthintHeight, String logopath,intLogosizemultiple)throwsException {File logofile=NewFile (Logopath); if(!logofile.exists () &&!Logofile.isfile ()) {            Throw NewException ("The specified logo image path does not exist!") "); }        Try {            //Read logoBufferedImage logo =Imageio.read (Logofile); //Set logo width height            intLogoheight = Qrcode.getheight ()/logosizemultiple; intLogowidth = Qrcode.getwidth ()/logosizemultiple; //set the location of the QR code image where the logo is placed            intx = (Qrcode.getwidth ()-logowidth)/2; inty = (qrcode.getheight ()-logoheight)/2; //New Empty ArtboardBufferedImage combined =Newbufferedimage (width, height, bufferedimage.type_int_rgb); //New BrushGraphics2D g =(graphics2d) combined.getgraphics (); //draw the QR code to the artboardG.drawimage (qrcode, 0, 0,NULL); //set opacity, completely opaque 1f, can set range 0.0f-1.0fG.setcomposite (Alphacomposite.getinstance (Alphacomposite.src_over, 1.0f)); //Draw LogoG.drawimage (logo, x, y, Logowidth, Logoheight,NULL); returncombined; } Catch(Exception e) {Throw Newruntimeexception (E.getmessage (), E); }    }        /*** Export to specified path *@authorLinwenli * @date 2018-08-23 12:59:03 *@paramBufferedImage *@paramfilepath Picture Save path *@paramFileName image file name *@paramformatname Picture Format *@return: Boolean*/     Public Static BooleanGenerateqrcodetopath (BufferedImage bufferedimage,string filePath, String fileName, String formatname) {//determines whether the path exists, does not exist, and createsFile Path =NewFile (FilePath); if(!path.exists ())        {Path.mkdirs (); }        //add slash after path        if(Filepath.lastindexof ("\ \")! = Filepath.length ()-1) {FilePath= FilePath + "\ \"; }        //full path combined for picture generationString Filefullpath = filePath + FileName + "." +FormatName; Booleanresult =false; Try {            //output picture file to the specified locationresult = Imageio.write (BufferedImage, FormatName,NewFile (Filefullpath)); } Catch(IOException e) {e.printstacktrace (); }        returnresult; }}
View Code

Then the test code:

     Public Static voidMain (string[] args) {String contents= "Two-dimensional code content"; intwidth = 220;//Two-dimensional code width        intheight = 220;//Two-dimensional code height        intmargin = 0;//Two-dimensional code marginString Logopath= "C:\\users\\mycomputer\\desktop\\logo.jpg";//logo Image Path        intLogosizemultiple = 3;//Two-dimensional code and logo size ratioString FilePath= "c:\\users\\mycomputer\\desktop\\";//Specifies the save path of the generated picture fileString fileName = "ImageName";//the generated picture file nameString formatname = "jpg";//generated picture format, customizable        Try {            //generate two-dimensional codeBufferedImage QRCode =Qrcodeutils.createqrcode (contents, width, height,margin); //Add logoQRCode =Qrcodeutils.createqrcodewithlogo (qrcode, width, height, logopath,logosizemultiple); //export to the specified path            Booleanresult =Qrcodeutils.generateqrcodetopath (QRCode, FilePath, FileName, FormatName); System.out.println ("Execution Result" +result); } Catch(Exception e) {e.printstacktrace (); }    }

Java uses zxing to generate/parse two-dimensional code images

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.