1. Basic class provides two-dimensional code generation tool class
Package Com.green.util;import Java.awt.image.bufferedimage;import Java.io.bytearrayoutputstream;import Java.io.file;import Java.io.ioexception;import Java.io.outputstream;import Javax.imageio.imageio;import Com.google.zxing.common.bitmatrix;public Final class Matrixtoimagewriter {private static final int BLACK = 0xff000000; private static final int white = 0xffffffff;private Matrixtoimagewriter () {}public static bufferedimage tobufferedimage (B Itmatrix 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 an image of format" + formAt + "to" + file);}} public static byte[] WriteToStream (Bitmatrix matrix, String format) throws IOException {Bytearrayoutputstream stream=new Bytearrayoutputstream (); BufferedImage image = Tobufferedimage (matrix); Imageio.write (image, format, stream)) {throw new IOException ("Could not write an image of format" + format);} return Stream.tobytearray ();}}
2. Invoking the tool method to get the binary of the picture
Package Com.green.util;import Java.io.file;import Java.io.ioexception;import java.util.hashtable;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;/** * @author Maybo * */public class Qrcodegenerator {public static byte[] Build (String content) throws IOException, writerexception { int width = 300;
int height = +; //??????????? String format = "gif"; Hashtable hints = new Hashtable (); //???????? Ñ??? Hints.put (Encodehinttype.character_set, "Utf-8"); Bitmatrix Bitmatrix = new Multiformatwriter (). Encode (content, barcodeformat.qr_code, width, height, hints); Return Matrixtoimagewriter.writetostream (Bitmatrix, format);}}
Java generates two-dimensional code via zxing