package com.zzl.controller.demo;import com.google.zxing.*;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.QRCodeWriter;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.charset.CharacterCodingException;import java.nio.charset.Charset;import java.nio.charset.CharsetEncoder;import java.util.Hashtable;/** * ClassObject
is the root of the class hierarchy. * Every class hasObject
as a superclass. All objects, * including arrays, implement the methods of this class. * * @author Administrator * @version 1.0 * @see * @since JDK1.7 ** History * Created by Administrator on 2017/12/11 0011. */public class QRcodeDemo { private static Hashtable hints = new Hashtable(); { //设置二维码排错率,可选L(7%) M(15%) Q(25%) H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q); } public static void main(String[] args) throws Exception{ String filePath = "C:\\Users\\Administrator\\Desktop\\1.jpg"; encode("http://www.baidu.com/", filePath); decode(filePath); } // qrcode 编码 public static void encode(String conent, String filePath) throws Exception{ BitMatrix matrix = null; int h = 200; int w = 200; QRCodeWriter writer = new QRCodeWriter(); try { matrix = writer.encode(conent, BarcodeFormat.QR_CODE, h, w, hints); File file = new File(filePath); MatrixToImageWriter.writeToFile(m, "PNG", file); } catch (com.google.zxing.WriterException e) { System.out.println(e.getMessage()); } } // qrcode 解码 public static void decode(String file) { try { Result result = null; BufferedImage image = null; image = ImageIO.read(new File(file)); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Hashtable
hints = new Hashtable (); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); result = new MultiFormatReader().decode(bitmap, hints); String rtn = result.getText(); System.out.println(rtn); System.out.println(rtn.length()); } catch (Exception ex) { System.out.println(ex.toString()); } }}
生成的二维码图片:
上面二维码旁边会有一圈白边的,如果要想去掉白边,加上下面这段代码
在输出前调用deleteWhite()方法:
m= deleteWhite(m);//删除白边MatrixToImageWriter.writeToFile(m, "PNG", file);
private static BitMatrix deleteWhite(BitMatrix matrix) { int[] rec = matrix.getEnclosingRectangle(); int resWidth = rec[2] + 1; int resHeight = rec[3] + 1; BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); resMatrix.clear(); for (int i = 0; i < resWidth; i++) { for (int j = 0; j < resHeight; j++) { if (matrix.get(i + rec[0], j + rec[1])) resMatrix.set(i, j); } } return resMatrix; }