Java generates two-dimensional code

Source: Internet
Author: User

Step by step with Java design to generate two-dimensional code

Go to http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html

In the age of the Internet of Things, the QR code is a very important thing, now no matter what things have to make a two-dimensional code sign, lest the outdated, the policeman did not use two-dimensional code recognition. Perhaps one day zoning card or hukou will be used to identify the two-dimensional code. Today's whim, see others have added two-dimensional code for their blog, I also want to make a test.

Mainly used to achieve two points:

1. Generate the QR code of any text.

2. Add an image to the middle of the QR code.

3.

Download QR Code pack.

First we have to download the Zxing.jar package, I use the 3.0 version of the core package

: Now it's migrated to Github:https://github.com/zxing/zxing/wiki/getting-started-developing,

Of course you can also download the jar package from the MAVEN repository: http://central.maven.org/maven2/com/google/zxing/core/

 PackageQrcodesoft;ImportJava.awt.Graphics2D;ImportJava.awt.geom.AffineTransform;ImportJava.awt.image.BufferedImage;ImportCom.google.zxing.LuminanceSource; Public classBufferedimageluminancesourceextendsLuminancesource {Private Finalbufferedimage image; Private Final intLeft ; Private Final inttop;  PublicBufferedimageluminancesource (bufferedimage image) { This(image, 0, 0, Image.getwidth (), Image.getheight ()); }     PublicBufferedimageluminancesource (bufferedimage image,intLeft ,intTopintWidthintheight) {        Super(width, height); intSourcewidth =image.getwidth (); intSourceheight =image.getheight (); if(left + width > Sourcewidth | | top + Height >sourceheight) {            Throw NewIllegalArgumentException ("Crop rectangle does not fit within image data."); }         for(inty = top; Y < top + height; y++) {             for(intx = left; X < left + width; X + +) {                if((Image.getrgb (x, y) & 0xff000000) = = 0) {Image.setrgb (x, Y,0xFFFFFFFF);//= White                }            }        }         This. Image =Newbufferedimage (Sourcewidth, Sourceheight, Bufferedimage.type_byte_gray);  This. Image.getgraphics (). DrawImage (image, 0, 0,NULL);  This. left =Left ;  This. top =top; }        Public byte[] GetRow (intYbyte[] row) {        if(Y < 0 | | y >=getheight ()) {            Throw NewIllegalArgumentException ("Requested row is outside the image:" +y); }        intwidth =getwidth (); if(Row = =NULL|| Row.length <width) {Row=New byte[Width]; } image.getraster (). getDataElements (left, top+ Y, Width, 1, Row); returnRow; }        Public byte[] Getmatrix () {intwidth =getwidth (); intHeight =getheight (); intArea = width *height; byte[] Matrix =New byte[Area];        Image.getraster (). getDataElements (left, top, width, height, matrix); returnMatrix; }        Public Booleaniscropsupported () {return true; }        PublicLuminancesource Crop (intLeftintTopintWidthintheight) {        return NewBufferedimageluminancesource (Image, This. Left +Left , This. Top +top, width, height); }        Public Booleanisrotatesupported () {return true; }        PublicLuminancesource rotatecounterclockwise () {intSourcewidth =image.getwidth (); intSourceheight =image.getheight (); AffineTransform Transform=NewAffineTransform (0.0,-1.0, 1.0,                0.0, 0.0, Sourcewidth); BufferedImage Rotatedimage=Newbufferedimage (Sourceheight, Sourcewidth, Bufferedimage.type_byte_gray); Graphics2D g=Rotatedimage.creategraphics (); G.drawimage (image, transform,NULL);        G.dispose (); intwidth =getwidth (); return NewBufferedimageluminancesource (rotatedimage, top, Sourcewidth-(left +width), getheight (), width); }}
Package Qrcodesoft;import Java.awt.basicstroke;import Java.awt.graphics;import java.awt.graphics2d;import Java.awt.image;import Java.awt.shape;import Java.awt.geom.roundrectangle2d;import java.awt.image.BufferedImage; Import Java.io.file;import java.io.outputstream;import Java.util.hashtable;import Java.util.random;import Javax.imageio.imageio;import Com.google.zxing.barcodeformat;import Com.google.zxing.binarybitmap;import Com.google.zxing.decodehinttype;import Com.google.zxing.encodehinttype;import Com.google.zxing.MultiFormatReader ; Import Com.google.zxing.multiformatwriter;import Com.google.zxing.result;import Com.google.zxing.common.bitmatrix;import Com.google.zxing.common.hybridbinarizer;import Com.google.zxing.qrcode.decoder.errorcorrectionlevel;public class Qrcodeutil {private static final String CHARSET = "U    Tf-8 ";    private static final String Format_name = "JPG";    Two dimensional code size private static final int qrcode_size = 300; Logo width private static final int width = 60;    Logo height private static final int height = 60;  private static BufferedImage CreateImage (string content, String Imgpath, Boolean needcompress) throws Exception        {Hashtable hints = new Hashtable ();        Hints.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H);        Hints.put (Encodehinttype.character_set, CHARSET);        Hints.put (Encodehinttype.margin, 1); Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (content, Barcodeformat.qr_code, Qrcode_size, Qrcode_si        ZE, hints);        int width = bitmatrix.getwidth ();        int height = bitmatrix.getheight ();        BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb); for (int x = 0; x < width; + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, y, Bi Tmatrix.get (x, y)?            0XFF000000:0XFFFFFFFF); }} if (Imgpath = = NULL | | ". Equals (Imgpath)) {return image;        }//Insert Picture qrcodeutil.insertimage (image, Imgpath, needcompress);    return image; } private static void Insertimage (BufferedImage source, String Imgpath, Boolean needcompress) throws Exce        ption {File File = new file (Imgpath); if (!file.exists ()) {System.err.println ("" +imgpath+ "the file does not exist!)            ");        Return        } Image src = imageio.read (new File (Imgpath));        int width = src.getwidth (null);        int height = src.getheight (null);            if (needcompress) {//Compress logo if (width > width) {width = width;            } if (height > height) {height = height;            } Image Image = Src.getscaledinstance (width, height, image.scale_smooth);            BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb); Graphics g = tag.getgraphicS (); G.drawimage (image, 0, 0, NULL);            Draw the reduced figure g.dispose ();        src = image;        }//Insert logo graphics2d graph = source.creategraphics ();        int x = (qrcode_size-width)/2;        int y = (qrcode_size-height)/2;        Graph.drawimage (src, x, y, width, height, null);        Shape shape = new Roundrectangle2d.float (x, y, Width, width, 6, 6);        Graph.setstroke (New Basicstroke (3f));        Graph.draw (Shape);    Graph.dispose ();  public static void Encode (string content, String Imgpath, String destpath, Boolean needcompress) throws        Exception {bufferedimage image = Qrcodeutil.createimage (content, Imgpath, needcompress);        Mkdirs (DestPath);        String file = new Random (). Nextint (99999999) + ". jpg";    Imageio.write (image, Format_name, new File (destpath+ "/" +file));           public static void Mkdirs (String destpath) {File file =new file (destpath); When the folder does notWhen present, Mkdirs automatically creates a multi-level directory, distinguished from mkdir.        (MkDir throws an exception if the parent directory does not exist) if (!file.exists () &&!file.isdirectory ()) {file.mkdirs ();        }} public static void encode (string content, String Imgpath, String destpath) throws Exception {    Qrcodeutil.encode (content, Imgpath, DestPath, false);        The public static void encode (string content, String DestPath, Boolean needcompress) throws Exception {    Qrcodeutil.encode (content, NULL, destpath, needcompress); public static void Encode (string content, String destpath) throws Exception {qrcodeutil.encode (content, Nu    ll, DestPath, false); public static void Encode (string content, String Imgpath, OutputStream output, Boolean needcompress) th        Rows Exception {bufferedimage image = Qrcodeutil.createimage (content, Imgpath, needcompress);    Imageio.write (image, format_name, output); } public static void encode (String content, OutputStream output) throws Exception {qrcodeutil.encode (content, NULL, output, false);        public static String decode (file file) throws Exception {bufferedimage image;        Image = Imageio.read (file);        if (image = = null) {return null;        } bufferedimageluminancesource Source = new Bufferedimageluminancesource (image);        Binarybitmap bitmap = new Binarybitmap (new Hybridbinarizer (source));        result result;        Hashtable hints = new Hashtable ();        Hints.put (Decodehinttype.character_set, CHARSET);        result = new Multiformatreader (). Decode (bitmap, hints);        String resultstr = Result.gettext ();    return resultstr;    public static string decode (string path) throws Exception {return Qrcodeutil.decode (new File);        public static void Main (string[] args) throws Exception {String text = "http://www.dans88.com.cn"; Qrcodeutil.encode (tExt, "d:/myworkdoc/my180.jpg", "D:/myworkdoc", true); }   }

  

Java generates two-dimensional code

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.