前言
ZXing,一个支持在图像中解码和生成条形码(如二维码、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的库。ZXing(“zebra crossing”)是一个开源的、多格式的、用Java实现的一维/二维条码图像处理库,具有到其他语言的端口。
GitHub地址,猛戳:https://github.com/zxing/zxing
API文档,猛戳:https://zxing.github.io/zxing/apidocs/index.html
介绍文档,猛戳:https://zxing.github.io/zxing/
Maven 依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
代码示例
/**
* 获取二维码
*
* @param qrcodeData
* @param httpServletResponse
*/
public void get(String qrcodeData, HttpServletResponse httpServletResponse) {
try {
int white = 0x000000;
int black = 0xFFFFFF;
String characterSet = "utf-8";
String imgFormat = "PNG";
// 二维码宽度
int qrcodeWidth = 256;
// 二维码高度
int qrcodeHeight = 256;
// 生命二维码对象
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, Object> hint = new EnumMap(EncodeHintType.class);
// 设置错误级别
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置字符编码
hint.put(EncodeHintType.CHARACTER_SET, characterSet);
// 设置边缘
hint.put(EncodeHintType.MARGIN, 0);
// 生成二维码
BitMatrix bitMatrix = qrCodeWriter.encode(qrcodeData, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hint);
int bitMatrixWidth = bitMatrix.getWidth();
int bitMatrixHeight = bitMatrix.getHeight();
BufferedImage qrcodeImg = new BufferedImage(bitMatrixWidth, bitMatrixHeight, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < bitMatrixWidth; x++) {
for (int y = 0; y < bitMatrixHeight; y++) {
qrcodeImg.setRGB(x, y, bitMatrix.get(x, y) ? white : black);
}
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(qrcodeImg, imgFormat, byteArrayOutputStream);
// 设置响应头
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.setContentType("image/png");
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
servletOutputStream.write(byteArrayOutputStream.toByteArray());
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}