添加依赖
<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>
二维码工具类
package com.ds.system.utils.report;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtils {
public static BitMatrix createCode(String content) throws IOException {
//二维码的宽高
int width = 200;
int height = 200;
//其他参数,如字符集编码
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//容错级别为H
hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
//白边的宽度,可取0~4
hints.put(EncodeHintType.MARGIN , 0);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
}
public static Boolean generateCode(BitMatrix matrix, String format, OutputStream stream){
try {
MatrixToImageWriter.writeToStream(matrix , format , stream);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
web测试
@GetMapping("/QR")
public void QR(HttpServletResponse response) throws IOException {
response.reset();
response.setContentType("image/jpg");
//不需要缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
ServletOutputStream outputStream = response.getOutputStream();
BitMatrix bitMatrix = QRCodeUtils.createCode("nihao");
QRCodeUtils.generateCode(bitMatrix , "jpg" , outputStream);
}
}