Zxing and QR code generation and parsing two-dimensional codes (general text)

Source: Internet
Author: User
Tags getmessage string format

first download the corresponding jar package, this example uses the Zxing2.2jar

Download Address: http://download.csdn.net/detail/gao36951/8161861

Zxing is a Google-provided analytical tool for barcode (one-dimensional code, two-dimensional code), which provides a method for generating and parsing two-dimensional codes,
See zxing example below Code:

Package com.zxing.create;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import java.io.IOException;


Import Java.util.HashMap;

Import Java.util.Map;

Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.Binarizer;
Import Com.google.zxing.BinaryBitmap;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.LuminanceSource;
Import Com.google.zxing.MultiFormatReader;
Import Com.google.zxing.MultiFormatWriter;
Import Com.google.zxing.Result;
Import com.google.zxing.WriterException;
Import Com.google.zxing.common.BitMatrix;
Import Com.google.zxing.common.HybridBinarizer;


Import Com.util.BufferedImageLuminanceSource; /** * @Description: (ordinary two-dimensional code generation) * @author: Relieved * @date: 2014-11-7 PM 04:42:35 * * public class Createpars Ecode {public static void main (String [] args) throws IOException, writerexception{createparsecode cpcode = new Crea
Teparsecode ();
Generate two-dimensional code cpcode.createcode (); Parsing two dimensional code Cpcode.parsEcode (New File ("d:/Two-dimensional code Generation/tdc-test.png"));
		/** * */public void Createcode () {String text = "http://blog.csdn.net/gao36951")
		int width = 300;
		int height = 300;
		Picture format for two-dimensional code String format = "png";
		/** * Set the parameters of the two-dimensional code * * * HASHMAP hints = new HashMap ();
		The content uses the encoding hints.put (Encodehinttype.character_set, "utf-8");
			try {Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (text,barcodeformat.qr_code,width,height,hints);
			Generate a two-dimensional code file OutputFile = new file ("D:" + file.separator + "Two-dimensional code generation" + File.separator + "tdc-test.png");
			
		Matrixtoimagewriter.writetofile (Bitmatrix, format, outputfile);
		catch (Exception e) {e.printstacktrace ();
        }/** * Two-dimensional code parsing * @param file/public void Parsecode (file file) {try
 
            {Multiformatreader Formatreader = new Multiformatreader ();
            if (!file.exists ()) {return; } BUfferedimage image = Imageio.read (file);
            Luminancesource Source = new Bufferedimageluminancesource (image);
            Binarizer Binarizer = new Hybridbinarizer (source);
 
            Binarybitmap Binarybitmap = new Binarybitmap (Binarizer);
            Map hints = new HashMap ();
 
            Hints.put (Encodehinttype.character_set, "UTF-8");
 
            Result result = Formatreader.decode (Binarybitmap, hints);
            System.out.println ("analytic result =" + result.tostring ());
            System.out.println ("Two-dimensional code format type =" + Result.getbarcodeformat ());
        System.out.println ("Two-dimensional code text content =" + Result.gettext ());
        catch (Exception e) {e.printstacktrace ();
 }
    }
}
generate and parse related tool class code:

Import Com.google.zxing.common.BitMatrix;
 Import Javax.imageio.ImageIO;
 Import Java.io.File;
 Import Java.io.OutputStream;
 Import java.io.IOException;
 
 
 Import Java.awt.image.BufferedImage;
   Public final class Matrixtoimagewriter {private static final int black = 0xff000000;
 
   private static final int white = 0xFFFFFFFF;  Private Matrixtoimagewriter () {} public static bufferedimage Tobufferedimage (Bitmatrix matrix) {int width =
     Matrix.getwidth ();
     int height = matrix.getheight ();
     BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb); for (int x = 0; x < width, x + +) {for (int y = 0; y < height; y++) {Image.setrgb (x, Y, Matrix.get x , y)?
       Black:white);
   } return image; public static void WriteToFile (Bitmatrix matrix, String format, file file) throws IOException {Buf
     Feredimage image = Tobufferedimage (matrix); if (! Imageio.write (image, forMat, file) {throw new IOException ("Could not write ' an image of the format" + format + "to" + file); } public static void WriteToStream (Bitmatrix matrix, String format, OutputStream stream) throws Ioexc
     eption {bufferedimage image = Tobufferedimage (matrix); if (!
     Imageio.write (image, format, stream)) {throw new IOException ("Could not write an image of format" + format); }
   }
 
 }


Package com.util;

Import Com.google.zxing.LuminanceSource;
Import Java.awt.Graphics2D;
Import Java.awt.geom.AffineTransform;

Import Java.awt.image.BufferedImage;
  Public final class Bufferedimageluminancesource extends Luminancesource {private final bufferedimage image;
  private final int left;

  private final int top;
  Public Bufferedimageluminancesource (bufferedimage image) {This (image, 0, 0, image.getwidth (), Image.getheight ());  Public Bufferedimageluminancesource (bufferedimage image, int left, int top, int width, int height) {Super (width,

    height);
    int sourcewidth = Image.getwidth ();
    int sourceheight = Image.getheight (); if (left + width > Sourcewidth | | top + height > sourceheight) {throw new IllegalArgumentException ("Crop rect

    Angle does not fit within image data. "); for (int y = top, y < top + height; y++) {for (int x = left; x < left + width; + +) {if (image.getr GB (x, y) & 0xff000000) = = 0){Image.setrgb (x, y, 0xFFFFFFFF);//= white}}
    } this.image = new BufferedImage (Sourcewidth, Sourceheight, Bufferedimage.type_byte_gray);
    This.image.getGraphics (). DrawImage (image, 0, 0, NULL);
    This.left = left;
  This.top = top; @Override public byte[] GetRow (int y, byte[] row) {if (Y < 0 | | | y >= getheight ()) {throw new Ille
    Galargumentexception ("Requested row is outside the image:" + y);
    int width = getwidth ();
    if (row = = NULL | | Row.length < width) {row = new Byte[width];
    } image.getraster (). getDataElements (left, top + y, width, 1, row);
  return row;
    @Override public byte[] Getmatrix () {int width = getwidth ();
    int height = getheight ();
    int area = width * height;
    byte[] Matrix = new Byte[area];
    Image.getraster (). getDataElements (left, top, width, height, matrix);
  return matrix; @Override public boolean iscropsupported () {true;
  @Override Public Luminancesource crop (int. left, int top, int width, int height) {return new Bufferedimagelu
  Minancesource (image, This.left + left, This.top + top, width, height);
  @Override public boolean isrotatesupported () {true;
    @Override public Luminancesource rotatecounterclockwise () {int sourcewidth = Image.getwidth ();

    int sourceheight = Image.getheight ();

    AffineTransform transform = new AffineTransform (0.0, -1.0, 1.0, 0.0, 0.0, sourcewidth);

    BufferedImage rotatedimage = new BufferedImage (Sourceheight, Sourcewidth, Bufferedimage.type_byte_gray);
    Graphics2D g = rotatedimage.creategraphics ();
    G.drawimage (image, transform, null);

    G.dispose ();
    int width = getwidth ();
  Return to New Bufferedimageluminancesource (Rotatedimage, Top, Sourcewidth-(left + width), getheight (), width); }

}
The resulting two-dimensional code is shown below:


The results of the analysis are as follows:


let's look at the QR code instance

Package com.qrcode.create;
/** * @ Author relieved * @ Creation Date November 7, 2014 * (using QRCode to generate two-dimensional code) * @ VERSION V 1.0 * * Import Java.awt.Color;
Import Java.awt.Graphics2D;
Import Java.awt.image.BufferedImage;

Import Java.io.File;

Import Javax.imageio.ImageIO;

Import Com.swetake.util.Qrcode; /** * Two-dimensional code generator */public class Qrcodeencoderhandler {/** * Generate two-dimensional code (qrcode) Picture * @param content * @param Imgpath */public void Encoderqrcode (string content, string Imgpath,int version) {try {QRC
            Ode Qrcodehandler = new QRCode (); Set the two-dimensional code error rate, optional L (7%), M (15%), Q (25%), H (30%), the higher the rate of error, the less information can be stored, but the requirements of two-dimensional code clarity Qrcodehandler.setqrcodeerrorcorrect (' M ')
            ;
            n represents a number, and a represents a character a-z,b representing other characters qrcodehandler.setqrcodeencodemode (' B ');
	    Version 1 is the 21*21 matrix, the version is 1, the two sides of the two-dimensional code increase by 4, so the version 7 is the 45*45 matrix, the highest version is 40, and the 177*177 Matrix Qrcodehandler.setqrcodeversion (version);
            int imgsize = + (version-1); System.out.println (content);

            byte[] Contentbytes = content.getbytes ("gb2312");
            BufferedImage bufimg = new BufferedImage (imgsize, imgsize, Bufferedimage.type_int_rgb);

            graphics2d GS = Bufimg.creategraphics ();
            Gs.setbackground (Color.White);

            Gs.clearrect (0, 0, imgsize, imgsize);

            Set Image Color > Black gs.setcolor (Color.Black);
            Setting offset without setting may cause parsing error int pixoff = 2;
            Output content > Two-dimensional code System.out.println (contentbytes.length); if (contentbytes.length > 0 && contentbytes.length < 130) {boolean[][] codeout = Qrcodehand
                Ler.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 {System.err.println ("qrcode content bytes Length ="
            + Contentbytes.length + "not in [0,130].");
            } gs.dispose ();

            Bufimg.flush ();

            File Imgfile = new file (Imgpath);

        Generate two-dimensional Code qrcode picture Imageio.write (bufimg, "PNG", imgfile);
        catch (Exception e) {e.printstacktrace ();
        }/** * @param args the command line arguments/public static void main (string[] args) {

        String Imgpath = "d:/Two-dimensional code generation/relieved_qrcode.png";

        String content = "http://blog.csdn.net/gao36951";
        Qrcodeencoderhandler handler = new Qrcodeencoderhandler ();

        Handler.encoderqrcode (content, imgpath,8);
    SYSTEM.OUT.PRINTLN ("Encoder qrcode success"); }
}



generate two-dimensional code as shown below


The parsing code is as follows:

Package com.qrcode.create.decreate;
/** * @ Author relieved * @ Creation Date November 7, 2014 * (parsing qrcode two-dimensional code) * @ VERSION V 1.0 * * Import java.awt.image.BufferedImage;
Import Java.io.File;

Import java.io.IOException;

Import Javax.imageio.ImageIO;
Import Jp.sourceforge.qrcode.QRCodeDecoder;
Import Jp.sourceforge.qrcode.data.QRCodeImage;

Import jp.sourceforge.qrcode.exception.DecodingFailedException; public class Qrcodedecoderhandler {/** * decoding two-dimensional code * @param imgpath * @return String * */Public S

        Tring Decoderqrcode (String imgpath) {//QRCode two-dimensional code picture file Files ImageFile = new file (Imgpath);
        BufferedImage bufimg = null;
        String decodeddata = null;

            try {bufimg = Imageio.read (ImageFile);
            Qrcodedecoder decoder = new Qrcodedecoder ();

        Decodeddata = new String (Decoder.decode (New J2seimage (bufimg)), "gb2312");
catch (IOException e) {System.out.println ("Error:" + e.getmessage ());            E.printstacktrace ();
            catch (Decodingfailedexception DfE) {System.out.println ("Error:" + dfe.getmessage ());
        Dfe.printstacktrace ();
    return decodeddata; }/** * @param args the command line arguments/public static void main (string[] args) {Qrco
        Dedecoderhandler handler = new Qrcodedecoderhandler ();
        String Imgpath = "d:/Two-dimensional code generation/relieved_qrcode.png";
        String decodercontent = Handler.decoderqrcode (Imgpath);
        System.out.println ("The analytic result is as follows:");
        System.out.println (decodercontent);
    System.out.println ("========decoder success!!!");

        Class J2seimage implements Qrcodeimage {BufferedImage bufimg;
        Public J2seimage (BufferedImage bufimg) {this.bufimg = bufimg;
        public int getwidth () {return bufimg.getwidth ();
        public int getheight () {return bufimg.getheight ();

}        public int GetPixel (int x, int y) {return Bufimg.getrgb (x, y); }

    }
}



The results of the analysis are shown below:


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.