参考地址: https://www.cnblogs.com/manusas/p/6801436.html
package com.wfz.zxing;
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.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.util.Map;
/**
* Created by Liang on 5/3/2017.
*/
public class ZxingUtils {
/**
* 生成二维码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public void encodeQRCode(String contents, int width, int height, String imgPath) {
Map hints = new Hashtable<>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try { //QR_CODE结尾的为生成二维码 要注意高度宽度 信息量越大 二维码越密集
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "png",
new FileOutputStream(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析二维码
*
* @param imgPath
* @return
*/
public String decodeQRCode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成条形码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
// int width = 105, height = 50; 长度很容易报错:NotFoundException
public void encodeBarCode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try { //条形码貌似只能写入条形码固定规则的信息
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter.writeToStream(bitMatrix, "png",
new FileOutputStream(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析条形码
*
* @param imgPath
* @return
*/
public String decodeBarCode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
/* Map hints = new Hashtable<>();
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);*/
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试:特别注意 高宽 容易报错:NotFoundException
public static void main(String[] args) throws Exception {
String imgPath = "D:\\test.png";
// 益达无糖口香糖的条形码
String contents = "6923450657713";
int width = 105, height = 50;
ZxingUtils handler = new ZxingUtils();
handler.encodeBarCode(contents, width, height, imgPath);
String barcode = handler.decodeBarCode(imgPath);
System.out.println(barcode);
handler.encodeQRCode("abc123中文@#\\", 200, 200, imgPath);
String qrcode = handler.decodeQRCode(imgPath);
System.out.println(qrcode);
}
这是我的工具类重要信息
// 条码编码规则设定(字符集)
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
// 条码编码
String info = strCode.toString(); //BarcodeFormat.PDF_417这个是加密的条形码信息
//info 是想要写入的信息 codeWidh,codeHeight是高度宽度
BitMatrix bm = new MultiFormatWriter().encode(info, BarcodeFormat.QR_CODE, codeWidth,
codeHeight, hints);
bm = deleteWhite(bm);// 去掉白边
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
// 输出条码到文件流
MatrixToImageWriter.writeToStream(bm, fileFormat, bos);
byte[] buffer = bos.toByteArray();
// 直接输出文件流到页面图片标签(需要Base64编码)
return ("data:image/png;base64," + (Base64.getEncoder()).encodeToString(buffer));
注:条形码信息规则应需要注意;
2018年6月28日 补充:
直接通过java Controller 返回二维码图片信息
引入jar包
com.google.zxing
core
3.3.2
Goodle提供一个jar包
引入jar之后,然后通过Contreller直接访问,即可直接返回二维码信息
package com.controller;
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;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;
@RestController
@RequestMapping(value = "/test")
public class UserController {
@RequestMapping(value = "aa")
public String cc(HttpServletResponse response) throws IOException, WriterException {
BufferedImage bi = Encode_QR_CODE("sadd");
ImageIO.write(bi, "jpg", response.getOutputStream());
return "2132131";
}
public static BufferedImage Encode_QR_CODE(String contents) throws IOException, WriterException {
// String contents = "ZXing 二维码内容1234!"; // 二维码内容
int width = 200; // 二维码图片宽度 300
int height = 200; // 二维码图片高度300
String format = "gif";// 二维码的图片格式 gif
Hashtable hints = new Hashtable();
// 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 内容所使用字符集编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
// hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要编码的内容
//编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
BarcodeFormat.QR_CODE,
width, //条形码的宽度
height, //条形码的高度
hints);//生成条形码时的一些配置,此项可选
// 生成二维码
return toBufferedImage(bitMatrix);
// MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
}
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;
}
private static final int BLACK = 0xFF000000;//用于设置图案的颜色
private static final int WHITE = 0xFFFFFFFF; //用于背景色
}