Generation and parsing code of Java QR code

Source: Internet
Author: User
Tags set background

Two-dimensional code, is a black-and-white plane geometry through the corresponding coding algorithm to record text, pictures, URLs and other information of the barcode picture. Such as

Two-dimensional code features:

1. High-density coding, large information capacity

Can hold up to 1850 uppercase letters or 2,710 digits or 1108 bytes, or more than 500 Chinese characters, about dozens of times times higher than the normal barcode information capacity.

2. Wide Coding Range

The bar code can be picture, voice, text, signature, fingerprint and other digital information can be encoded, with bar code, can be expressed in multiple languages, can represent image data.

3. Strong fault tolerance, with error correction function

This makes the two-dimensional barcode due to perforation, fouling and other causes of local damage, the same can be correctly read, the damage area of up to 50% can still recover information.

4. High decoding reliability

It is more than the normal code decoding error rate of two out of 10,000 is much lower, the BER is not more than one out of 10,000.

5. Encryption measures can be introduced

Confidentiality, security is good.

6. Low cost, easy to manufacture, durable

Because of these characteristics, two-dimensional code is now more and more popular, the application is more and more widely (see Baidu Encyclopedia, Introduction is not the focus of this article), so master how to develop two-dimensional code is very good knowledge reserves, so this blog will explain how to generate and parse the two-dimensional code.

First, Java

Jar Package Required: Qrcode.jar

Twodimensioncode class: Two-dimensional code operation core class

Twodimensioncode.java

Package com. Qrcode.demo;import Java.awt.color;import Java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.io.outputstream;import Javax.imageio.imageio;import Jp.sourceforge.qrcode.qrcodedecoder;import Jp.sourceforge.qrcode.exception.decodingfailedexception;import Com.swetake.util.qrcode;public Class Twodimensioncode {/** * generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture Path */Public V    OID Encoderqrcode (string content, String Imgpath) {This.encoderqrcode (content, Imgpath, "PNG", 7); }/** * generate QR Code (qrcode) picture * @param Content Store contents * @param output stream */public void Encoderqrcode (S    Tring content, OutputStream output) {this.encoderqrcode (content, Output, "PNG", 7);    }/** * generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype picture Type */ Public void Encoderqrcode (string content, String Imgpath, String imgtype) {This.encoderqrcode (content, Imgpath, Imgtype,    7); }/** * generate QR Code (qrcode) picture * @param content storage * @param output stream * @param imgtype Picture type */P  ublic void Encoderqrcode (string content, OutputStream output, string imgtype) {this.encoderqrcode (content, output,    Imgtype, 7); /** * Generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype picture type * @param            Size QR Code dimensions */public void Encoderqrcode (string content, String Imgpath, string imgtype, int size) {try {                        BufferedImage bufimg = This.qrcodecommon (content, imgtype, size);            File Imgfile = new file (Imgpath);        Generate two-dimensional code qrcode picture Imageio.write (bufimg, Imgtype, imgfile);        } catch (Exception e) {e.printstacktrace (); }}/** * generate QR Code (qrcode) image * @param content storage * @param output inputOut stream * @param imgtype Picture type * @param size QR Code dimensions */public void Encoderqrcode (String content, OutputStream OUTP            UT, String imgtype, int size) {try {bufferedimage bufimg = This.qrcodecommon (content, imgtype, size);        Generate two-dimensional code qrcode picture Imageio.write (bufimg, imgtype, Output);        } catch (Exception e) {e.printstacktrace ();     }}/** * Common way to generate a QR code (qrcode) picture * @param content storage * @param imgtype Picture type * @param size QR code dimension  * @return */Private BufferedImage Qrcodecommon (string content, string imgtype, int size) {BufferedImage        Bufimg = null;            try {qrcode Qrcodehandler = new QRCode ();            Set the two-dimensional code error rate, optional L (7%), M (15%), Q (25%), H (30%), the higher the error rate can be stored less information, but the two-dimensional code clarity requirements of the smaller qrcodehandler.setqrcodeerrorcorrect (' M ');            Qrcodehandler.setqrcodeencodemode (' B ');    Set the size of the two-dimensional code, the value range 1-40, the larger the value, the larger the size, the larger the information can be stored qrcodehandler.setqrcodeversion (size);        Get the byte array of the content, set the encoding format byte[] contentbytes = content.getbytes ("Utf-8");            Image size Int imgsize = + * (size-1);            bufimg = new BufferedImage (imgsize, imgsize, Bufferedimage.type_int_rgb);            graphics2d GS = Bufimg.creategraphics ();            Set Background color gs.setbackground (color.white);            Gs.clearrect (0, 0, imgsize, imgsize);            Set Image Color > BLACK gs.setcolor (color.black);            Setting the offset, not setting may cause parsing error int pixoff = 2; Output content > QR code if (contentbytes.length > 0 && contentbytes.length <) {Boolea                n[][] Codeout = Qrcodehandler.calqrcode (contentbytes);                        for (int i = 0, i < codeout.length; i++) {for (int j = 0; J < Codeout.length; J + +) {                        if (Codeout[j][i]) {Gs.fillrect (J * 3 + Pixoff, I * 3 + Pixoff, 3, 3);          }          }}} else {throw new Exception ("qrcode content bytes length =" + con            Tentbytes.length + "Not in [0, 800].");            } gs.dispose ();        Bufimg.flush ();        } catch (Exception e) {e.printstacktrace ();    } return bufimg; }/** * Parse QR code (qrcode) * @param imgpath Picture Path * @return * */public string Decoderqrcode (string IMGP        ATH) {//qrcode QR code image file ImageFile = "New File" (Imgpath);        BufferedImage bufimg = null;        String content = null;            try {bufimg = Imageio.read (ImageFile);            Qrcodedecoder decoder = new Qrcodedecoder ();         Content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), "Utf-8");            } catch (IOException e) {System.out.println ("Error:" + e.getmessage ());        E.printstacktrace (); } catch (Decodingfailedexception DfE) {System.out.println ("ERror: "+ dfe.getmessage ());        Dfe.printstacktrace ();    } return content; }/** * Parse QR code (QRCODE) * @param input stream * @return */public String Decoderqrcode (InputStream in        Put) {BufferedImage bufimg = null;        String content = null;            try {bufimg = Imageio.read (input);            Qrcodedecoder decoder = new Qrcodedecoder ();         Content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), "Utf-8");            } catch (IOException e) {System.out.println ("Error:" + e.getmessage ());        E.printstacktrace ();            } catch (Decodingfailedexception DfE) {System.out.println ("Error:" + dfe.getmessage ());        Dfe.printstacktrace ();    } return content;        } public static void Main (string[] args) {String Imgpath = "E:/5.jpg";        String encodercontent = "Try";        String content= "E:/5.jpg"; Twodimensioncode handler = new TwodimensIoncode ();        Handler.encoderqrcode (Encodercontent, Imgpath, "PNG");            /*try {outputstream output = new FileOutputStream (Imgpath);        Handler.encoderqrcode (content, output);        } catch (Exception e) {e.printstacktrace ();                        }*/System.out.println ("========encoder success");        String decodercontent = Handler.decoderqrcode (Imgpath);        System.out.println ("Parse the result as follows:");        System.out.println (decodercontent);    System.out.println ("========decoder success!!!"); }    }
Package com. Qrcode.demo;import Java.awt.color;import Java.awt.graphics2d;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.io.outputstream;import Javax.imageio.imageio;import Jp.sourceforge.qrcode.qrcodedecoder;import Jp.sourceforge.qrcode.exception.decodingfailedexception;import Com.swetake.util.qrcode;public Class Twodimensioncode {/** * generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture Path */Public V    OID Encoderqrcode (string content, String Imgpath) {This.encoderqrcode (content, Imgpath, "PNG", 7); }/** * generate QR Code (qrcode) picture * @param Content Store contents * @param output stream */public void Encoderqrcode (S    Tring content, OutputStream output) {this.encoderqrcode (content, Output, "PNG", 7);    }/** * generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype picture Type */ Public void Encoderqrcode (string content, String Imgpath, String imgtype) {This.encoderqrcode (content, Imgpath, Imgtype,    7); }/** * generate QR Code (qrcode) picture * @param content storage * @param output stream * @param imgtype Picture type */P  ublic void Encoderqrcode (string content, OutputStream output, string imgtype) {this.encoderqrcode (content, output,    Imgtype, 7); /** * Generate QR Code (qrcode) picture * @param Content Store Contents * @param imgpath Picture path * @param imgtype picture type * @param            Size QR Code dimensions */public void Encoderqrcode (string content, String Imgpath, string imgtype, int size) {try {                        BufferedImage bufimg = This.qrcodecommon (content, imgtype, size);            File Imgfile = new file (Imgpath);        Generate two-dimensional code qrcode picture Imageio.write (bufimg, Imgtype, imgfile);        } catch (Exception e) {e.printstacktrace (); }}/** * generate QR Code (qrcode) image * @param content storage * @param output inputOut stream * @param imgtype Picture type * @param size QR Code dimensions */public void Encoderqrcode (String content, OutputStream OUTP            UT, String imgtype, int size) {try {bufferedimage bufimg = This.qrcodecommon (content, imgtype, size);        Generate two-dimensional code qrcode picture Imageio.write (bufimg, imgtype, Output);        } catch (Exception e) {e.printstacktrace ();     }}/** * Common way to generate a QR code (qrcode) picture * @param content storage * @param imgtype Picture type * @param size QR code dimension  * @return */Private BufferedImage Qrcodecommon (string content, string imgtype, int size) {BufferedImage        Bufimg = null;            try {qrcode Qrcodehandler = new QRCode ();            Set the two-dimensional code error rate, optional L (7%), M (15%), Q (25%), H (30%), the higher the error rate can be stored less information, but the two-dimensional code clarity requirements of the smaller qrcodehandler.setqrcodeerrorcorrect (' M ');            Qrcodehandler.setqrcodeencodemode (' B ');    Set the size of the two-dimensional code, the value range 1-40, the larger the value, the larger the size, the larger the information can be stored qrcodehandler.setqrcodeversion (size);        Get the byte array of the content, set the encoding format byte[] contentbytes = content.getbytes ("Utf-8");            Image size Int imgsize = + * (size-1);            bufimg = new BufferedImage (imgsize, imgsize, Bufferedimage.type_int_rgb);            graphics2d GS = Bufimg.creategraphics ();            Set Background color gs.setbackground (color.white);            Gs.clearrect (0, 0, imgsize, imgsize);            Set Image Color > BLACK gs.setcolor (color.black);            Setting the offset, not setting may cause parsing error int pixoff = 2; Output content > QR code if (contentbytes.length > 0 && contentbytes.length <) {Boolea                n[][] Codeout = Qrcodehandler.calqrcode (contentbytes);                        for (int i = 0, i < codeout.length; i++) {for (int j = 0; J < Codeout.length; J + +) {                        if (Codeout[j][i]) {Gs.fillrect (J * 3 + Pixoff, I * 3 + Pixoff, 3, 3);          }          }}} else {throw new Exception ("qrcode content bytes length =" + con            Tentbytes.length + "Not in [0, 800].");            } gs.dispose ();        Bufimg.flush ();        } catch (Exception e) {e.printstacktrace ();    } return bufimg; }/** * Parse QR code (qrcode) * @param imgpath Picture Path * @return * */public string Decoderqrcode (string IMGP        ATH) {//qrcode QR code image file ImageFile = "New File" (Imgpath);        BufferedImage bufimg = null;        String content = null;            try {bufimg = Imageio.read (ImageFile);            Qrcodedecoder decoder = new Qrcodedecoder ();         Content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), "Utf-8");            } catch (IOException e) {System.out.println ("Error:" + e.getmessage ());        E.printstacktrace (); } catch (Decodingfailedexception DfE) {System.out.println ("ERror: "+ dfe.getmessage ());        Dfe.printstacktrace ();    } return content; }/** * Parse QR code (QRCODE) * @param input stream * @return */public String Decoderqrcode (InputStream in        Put) {BufferedImage bufimg = null;        String content = null;            try {bufimg = Imageio.read (input);            Qrcodedecoder decoder = new Qrcodedecoder ();         Content = new String (Decoder.decode (New Twodimensioncodeimage (bufimg)), "Utf-8");            } catch (IOException e) {System.out.println ("Error:" + e.getmessage ());        E.printstacktrace ();            } catch (Decodingfailedexception DfE) {System.out.println ("Error:" + dfe.getmessage ());        Dfe.printstacktrace ();    } return content;        } public static void Main (string[] args) {String Imgpath = "E:/5.jpg";        String encodercontent = "Try";        String content= "E:/5.jpg"; Twodimensioncode handler = new TwodimensIoncode ();        Handler.encoderqrcode (Encodercontent, Imgpath, "PNG");            /*try {outputstream output = new FileOutputStream (Imgpath);        Handler.encoderqrcode (content, output);        } catch (Exception e) {e.printstacktrace ();                        }*/System.out.println ("========encoder success");        String decodercontent = Handler.decoderqrcode (Imgpath);        System.out.println ("Parse the result as follows:");        System.out.println (decodercontent);    System.out.println ("========decoder success!!!"); }    }

Twodimensioncodeimage.java

Package com. Qrcode.demo;import Java.awt.image.bufferedimage;import Jp.sourceforge.qrcode.data.qrcodeimage;public Class Twodimensioncodeimage implements Qrcodeimage {    bufferedimage bufimg;        Public Twodimensioncodeimage (BufferedImage bufimg) {        this.bufimg = bufimg;    }        @Override public    int getheight () {        return bufimg.getheight ();    }    @Override public    int GetPixel (int x, int y) {        return Bufimg.getrgb (x, y);    }    @Override public    int getwidth () {        return bufimg.getwidth ();}    }

Generation and parsing code of Java QR 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.