Java generates two-dimensional code in three ways:
1: Using Swetakeqrcode to generate two-dimensional code in a Java project
http://swetake.com/qr/
or Http://sourceforge.jp/projects/qrcode/downloads/28391/qrcode.zip.
This was written by the Japanese and generated by our common square QR code.
Can be used in Chinese such as: 5677777GHJJJJJ
2: Use barcode4j to generate barcodes and QR codes
BARCODE4J Website: http://sourceforge.net/projects/barcode4j/
BARCODE4J is a two-dimensional code generation algorithm that uses Datamatrix to support the QR algorithm
Datamatrix is a European and American standard. QR is the standard for Japan,
Barcode4j are generally generated as rectangles.
such as: 88777alec000yan
This blog is very clear about this aspect:
http://baijinshan.iteye.com/blog/1004554
3, now specific introduction of the third is also a frequent use of the way: the use of zxing to generate two-dimensional code
Zxing is provided by Google on the bar code (one-dimensional code, two-dimensional code) of the Analytic tool, provides a two-dimensional code generation and parsing methods, and now I briefly introduce the use of Java zxing Generation and parsing of the QR code.
First step: Add the Zxing-core.jar package to the project.
The second step is to add the following three Java files, three file functions such as the following:
Matrixtoimagewriter.java generate two-dimensional code images.
Bufferedimageluminancesource.java parse two-dimensional code image.
Barcodefactory.java generates a QR code with an avatar.
Matrixtoimagewriter.java
Import Com.google.zxing.barcodeformat;import Com.google.zxing.encodehinttype;import Com.google.zxing.multiformatwriter;import Com.google.zxing.common.bitmatrix;import Javax.imageio.ImageIO;import Java.io.file;import Java.io.outputstream;import Java.io.ioexception;import Java.util.hashtable;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; + +) {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 {bufferedimage image = Tobuf Feredimage (matrix); if (! Imageio.write (image, format, file)) {throw new IOException ("Could not write a image of format" + format + "to" + file) ;}} public static void WriteToStream (Bitmatrix matrix, String format, OutputStream stream) throws IOException {BufferedImage I Mage = Tobufferedimage (matrix); Imageio.write (image, format, stream)) {throw new IOException ("Could not write an image of format" + format);}} public static void Main (string[] args) throws Exception {String Text = "Two-dimensional code content, can be a link can also be text"; int width = 300;int height = 30 0; Hashtable hints = new Hashtable () hints.put (Encodehinttype.character_set, "utf-8");//The encoding used for the content Bitmatrix Bitmatrix = new M Ultiformatwriter (). Encode (text, barcodeformat.qr_code, width, height, hints); File OutputFile = new file ("e:/qrtest/generates ordinary QR code. jpg");//file.separatorstring format = "JPG";//QR code picture formats MatrIxtoimagewriter.writetofile (Bitmatrix, format, outputFile);}}
Bufferedimageluminancesource.java
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.Result; Import Com.google.zxing.common.hybridbinarizer;import Java.awt.graphics2d;import java.awt.geom.AffineTransform; Import Java.awt.image.bufferedimage;import java.io.file;import Java.util.hashmap;import Java.util.Map;import Javax.imageio.imageio;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); NT Sourcewidth = Image.getwidth (); int sourceheight = Image.getheight (); if (left + width > Sourcewidth | | top + height & Gt Sourceheight) {ThrowNew IllegalArgumentException ("Crop rectangle does not fit within image data."); for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; + +) {if (Image.getrgb (x, y) & 0 xFF000000) = = 0) {Image.setrgb (x, y, 0xFFFFFFFF);//= White}}}this.image = new BufferedImage (Sourcewidth, Sourceheight, B Ufferedimage.type_byte_gray); This.image.getGraphics (). DrawImage (image, 0, 0, null); this.left = Left;this.top = top;} @Overridepublic byte[] GetRow (int y, byte[] row) {if (Y < 0 | | y >= getheight ()) {throw new illegalargumentexception ("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; @Overridepublic byte[] Getmatrix () {int width = getwidth (); int height = getheight (); int area = width * height;byte[] Matri x = new Byte[area];image.getraster (). getDataElements (left, top, width, height, matrix); return matrix;} @OvErridepublic Boolean iscropsupported () {return true;} @Overridepublic luminancesource crop (int left, int top, int width, int height) {return new Bufferedimageluminancesource (IM Age, This.left + left, This.top + top, width, height);} @Overridepublic Boolean isrotatesupported () {return true;} @Overridepublic 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 new Bufferedimageluminancesource (Rotatedimage, Top, Sourcewidth-(left + width), getheight (), width);} public static void Main (string[] args) {//parse QR code try {multiformatreader Formatreader = new Multiformatreader (); String FilePath = "e:/qrtest/generates ordinary QR code. JPG"; File File = NEW File (FilePath); 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 ("result =" + result.tostring ()); System.out.println ("Resultformat =" + Result.getbarcodeformat ()); System.out.println ("Resulttext =" + Result.gettext ());} catch (Exception e) {e.printstacktrace ();}}}
Barcodefactory.java
Import Java.awt.color;import java.awt.graphics2d;import Java.awt.image;import Java.awt.geom.affinetransform;import Java.awt.image.affinetransformop;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.encodehinttype;import Com.google.zxing.MultiFormatWriter; Import Com.google.zxing.writerexception;import Com.google.zxing.common.bitmatrix;import Com.google.zxing.qrcode.decoder.errorcorrectionlevel;public class Barcodefactory {//Picture width general private static final int Image_width = 80;private static final int image_height = 80;private static final int image_half_width = IMAGE_WIDTH/2;PR ivate static final int frame_width = 2;//Two-dimensional code writer private static Multiformatwriter mutiwriter = new Multiformatwriter ();/** * Embed Srcimagepath into destimagepath */public static void Encode (string content, int width, int height, string srcimagepath, St Ring Destimagepath) {try {imageio.write (Genbarcode (content, width, height, srcimagepath), "JPG", new File (Destimagepath));} catch (IOException e) {e.printstacktrace ();} catch (Writerexception e) {e.printstacktrace ()}} private static BufferedImage Genbarcode (string content, int width, int height, string srcimagepath) throws Writerexception , IOException {//Read source image BufferedImage Scaleimage = scale (Srcimagepath, Image_width, Image_height, true); int[][] SrcPixels = new Int[image_width][image_height];for (int i = 0; i < scaleimage.getwidth (); i++) {for (int j = 0; J < scaleimage . GetHeight (); J + +) {Srcpixels[i][j] = Scaleimage.getrgb (i, j);}} Map<encodehinttype, object> hint = new Hashmap<encodehinttype, object> (); Hint.put ( Encodehinttype.character_set, "Utf-8"); Hint.put (Encodehinttype.error_correction, ErrorCorrectionLevel.H);// Generate two-dimensional code Bitmatrix matrix = mutiwriter.encode (content, Barcodeformat.qr_code, width, height, hint);//two-dimensional matrix to one-dimensional pixel group int HALFW = Matrix.getwidth ()/2;int HALFH =Matrix.getheight ()/2;int[] pixels = new Int[width * height];for (int y = 0; y < matrix.getheight (); y++) {for (int x = 0; x < Matrix.getwidth (); X + +) {//Read picture if (× > halfw-image_half_width && x < HALFW + image_half_width && y > Halfh-imag e_half_width&& y < HALFH + image_half_width) {Pixels[y * WIDTH + x] = SRCPIXELS[X-HALFW + image_half_width][y -HALFH + image_half_width];} Form a border in the picture four weeks else if ((x > Halfw-image_half_width-frame_width && x < Halfw-image_half_width + Frame_wid th&& y > Halfh-image_half_width-frame_width && y < HALFH + image_half_width + frame_width) | | (x > HALFW + image_half_width-frame_width && x < HALFW + image_half_width + frame_width&& y > H Alfh-image_half_width-frame_width && y < HALFH + image_half_width + frame_width) | | (x > Halfw-image_half_width-frame_width && x < HALFW + Image_half_width + frame_width&& Y > Halfh-image_half_width-frame_width && y < halfh-image_half_width + frame_width) | | (x > Halfw-image_half_width-frame_width && x < HALFW + image_half_width + frame_width&& y > H ALFH + image_half_width-frame_width && y < HALFH + image_half_width + frame_width) {Pixels[y * WIDTH + x] = 0XFFFFFFF;} else {//here can change the color of the two-dimensional code, the ability to make two-dimensional code and background color; Pixels[y * width + x] = Matrix.get (x, y)? 0xff000000:0xfffffff;}}} BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb); Image.getraster (). setdataelements (0, 0, width, height, pixels); return image;} /** * Scales the incoming original image by height and width. Generate an icon that meets the requirements * * @param srcimagefile * source file Address * @param height * Target Height * @param width * Target width * @param Hasfiller * If the ratio is incorrect when the filler is required: true for filler; False for non-filler; * @throws ioexception */private static bufferedimage scale (String srcimagefile, int height, int width, boolean hasfiller) Throws IOException {Double ratio = 0.0; Scale file File = new file (srcimagefile); BufferedImage srcimage = imageio.read (file), Image destimage = srcimage.getscaledinstance (width, height, Bufferedimage.scale_smooth);//Calculate proportional if ((Srcimage.getheight () > height) | | (Srcimage.getwidth () > width)) {if (Srcimage.getheight () > Srcimage.getwidth ()) {ratio = (new Integer (height)). Doublevalue ()/Srcimage.getheight () ;} else {ratio = (new Integer (width)). Doublevalue ()/Srcimage.getwidth ();} Affinetransformop op = new Affinetransformop (affinetransform.getscaleinstance (ratio, ratio), null);d Estimage = Op.filter (srcimage, null);} if (Hasfiller) {//filler bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rgb); Graphics2D graphic = Image.creategraphics (); Graphic.setcolor (Color.White); graphic.fillrect (0, 0, width, height); if ( width = = Destimage.getwidth (null)) Graphic.drawimage (destimage, 0, (Height-destimage.getheight (NULL))/2, Destimage.getwidth (NULL), destimage.getheight (null), color.white, null); ElsegraPhic.drawimage (Destimage, (Width-destimage.getwidth (NULL))/2, 0, destimage.getwidth (null), Destimage.getheight ( NULL), Color.White, null), Graphic.dispose ();d estimage = image;} Return (BufferedImage) destimage;} public static void Main (string[] args) {//src.jpg is the Avatar file Barcodefactory.encode ("http://www.baidu.com", "e:/ Qrtest/src.jpg "," e:/qrtest/generates a QR code with avatar. jpg ");}}
Java implementation of two-dimensional code technology discussion.