QR code generation Tool Class Java edition

Source: Internet
Author: User

Note: Here I do not provide the path of the required jar package, I will display all the referenced jar packages, Google

 PackageCom.net.util;ImportJava.awt.BasicStroke;ImportJava.awt.Graphics;ImportJava.awt.Graphics2D;ImportJava.awt.Image;ImportJava.awt.Shape;ImportJava.awt.geom.RoundRectangle2D;ImportJava.awt.image.BufferedImage;ImportJava.io.File;ImportJava.io.OutputStream;Importjava.util.Hashtable;ImportJava.util.Random;ImportJavax.imageio.ImageIO;ImportCom.google.zxing.BarcodeFormat;ImportCom.google.zxing.BinaryBitmap;ImportCom.google.zxing.DecodeHintType;ImportCom.google.zxing.EncodeHintType;ImportCom.google.zxing.MultiFormatReader;ImportCom.google.zxing.MultiFormatWriter;ImportCom.google.zxing.Result;ImportCom.google.zxing.common.BitMatrix;ImportCom.google.zxing.common.HybridBinarizer;ImportCom.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/******************************************************************************** * Description: Two-dimensional code making tool class *@authorZhangdi *@version1.0*/ Public classQrcodeutil {Private Static FinalString CHARSET = "Utf-8"; Private Static FinalString format_name = "JPG"; //Two-dimensional code size    Private Static Final intQrcode_size = 300; //logo Width    Private Static Final intWIDTH = 60; //Logo Height    Private Static Final intHEIGHT = 60; /*** Generate QR Code *@paramContent Source Contents *@paramImgpath generate QR Code save path *@paramneedcompress If you want to compress *@returnreturn QR code image *@throwsException*/      Private StaticBufferedImage createimage (string content, String Imgpath,Booleanneedcompress)throwsException {Hashtable hints=NewHashtable ();          Hints.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H);          Hints.put (Encodehinttype.character_set, CHARSET); Hints.put (Encodehinttype.margin,1); Bitmatrix Bitmatrix=NewMultiformatwriter (). Encode (content, Barcodeformat.qr_code, qrcode_size, qrcode_size, hints); intwidth =bitmatrix.getwidth (); intHeight =bitmatrix.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, Bitmatrix.get (x, y)? 0xff000000:0xffffffff); }          }          if(Imgpath = =NULL|| "". Equals (Imgpath)) {              returnimage; }          //Insert Pictureqrcodeutil.insertimage (image, Imgpath, needcompress); returnimage; }        /*** Insert a picture in the generated QR code *@paramSource *@paramImgpath *@paramneedcompress *@throwsException*/      Private Static voidInsertimage (bufferedimage source, String Imgpath,Booleanneedcompress)throwsException {File file=NewFile (Imgpath); if(!file.exists ()) {System.err.println ("+ Imgpath +" The file does not exist! "); return; } Image src= Imageio.read (NewFile (Imgpath)); intwidth = src.getwidth (NULL); intHeight = src.getheight (NULL); if(needcompress) {//Compression logo            if(Width >WIDTH) {Width=WIDTH; }              if(Height >HEIGHT) {Height=HEIGHT; } Image Image=src.getscaledinstance (width, height, image.scale_smooth); BufferedImage Tag=Newbufferedimage (width, height, bufferedimage.type_int_rgb); Graphics g=Tag.getgraphics (); G.drawimage (Image,0, 0,NULL);//draw a zoomed-out diagramG.dispose (); SRC=image; }          //Insert LogoGraphics2D graph =Source.creategraphics (); intx = (qrcode_size-width)/2; inty = (qrcode_size-height)/2; Graph.drawimage (src, x, y, width, height,NULL); Shape Shape=NewRoundrectangle2d.float (x, y, Width, width, 6, 6); Graph.setstroke (NewBasicstroke (3f));          Graph.draw (Shape);      Graph.dispose (); }        /*** Create a QR code with logo and save to disk *@paramcontent *@paramImgpath logo image *@paramDestPath *@paramneedcompress *@throwsException*/       Public Staticstring encode (string content, String Imgpath, String destpath,Booleanneedcompress)throwsException {bufferedimage image=qrcodeutil.createimage (content, Imgpath, needcompress);          Mkdirs (DestPath); String file=NewRandom (). Nextint (99999999) + ". jpg";//generate random file namesImageio.write (image, Format_name,NewFile (DestPath + "/" +file)); returnfile; }         Public Static voidmkdirs (String destpath) {File file=NewFile (DestPath); //when a folder does not exist, Mkdirs automatically creates a multi-tiered directory, distinguished from mkdir. (MkDir throws an exception if the parent directory does not exist)        if(!file.exists () &&!file.isdirectory ())          {File.mkdirs (); }      }         Public Static voidEncode (string content, String Imgpath, String destpath)throwsException {qrcodeutil.encode (content, Imgpath, DestPath,false); }         Public Static voidEncode (string content, String destpath,Booleanneedcompress)throwsException {qrcodeutil.encode (content,NULL, DestPath, needcompress); }         Public Static voidEncode (string content, String destpath)throwsException {qrcodeutil.encode (content,NULL, DestPath,false); }         Public Static voidEncode (string content, String Imgpath, OutputStream output,Booleanneedcompress)throwsException {bufferedimage image=qrcodeutil.createimage (content, Imgpath, needcompress);      Imageio.write (image, format_name, output); }         Public Static voidEncode (String content, outputstream output)throwsException {qrcodeutil.encode (content,NULL, Output,false); }              /*** from the QR code, parse the data *@paramfile QR code picture files *@returnreturns the data value parsed from the QR code *@throwsException*/       Public StaticString decode (file file)throwsException {bufferedimage image; Image=imageio.read (file); if(Image = =NULL) {              return NULL; } Bufferedimageluminancesource Source=NewBufferedimageluminancesource (image); Binarybitmap Bitmap=NewBinarybitmap (NewHybridbinarizer (source));          result result; Hashtable hints=NewHashtable ();          Hints.put (Decodehinttype.character_set, CHARSET); Result=NewMultiformatreader (). Decode (bitmap, hints); String ResultStr=Result.gettext (); returnResultStr; }         Public StaticString decode (String path)throwsException {returnQrcodeutil.decode (NewFile (path)); }  //try {////String Text = "Http://weifeng.nethangzhou.com/wf/weixin/getUserInfoCode"; //String Text = "http://www.lechuan100.com/plugin.php?id=haven_article&mod=my&aid=21 "; ////Create a QR code with logo////Qrcodeutil.encode (text, "D:/730.png", "D:/wfqrcode", true);////Create a QR code with no logo//Qrcodeutil.encode (Text, "", "D:/wfqrcode", true); //////Specify a QR code image to parse the return data////System.out.println (Qrcodeutil.decode ("d:/wps/75040887.jpg")); //} catch (Exception e) {//e.printstacktrace ();//}  }

QR code generation Tool Class Java edition

Related Article

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.