二维码生成URL链接
1. pom.xml导入zxing依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
2. 工具类代码如下:
/**
* 生成二维码图片流
*/
public class QrCodeImageUtil {
public static BitMatrix generateQRCodeStream(String content, HttpServletResponse response) {
//给相应添加头部信息,主要告诉浏览器返回的是图片流
response.setHeader("Cache-Control", "no-store");
// 不设置缓存
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/png");
//设置图片的文字编码以及内边框
Map<EncodeHintType, Object> hints = new HashMap<>();
//编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//边框距
hints.put(EncodeHintType.MARGIN, 2);
BitMatrix bitMatrix;
try {
//参数分别为:编码内容、编码类型、图片宽度、图片高度,设置参数
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
} catch (WriterException e) {
e.printStackTrace();
return null;
}
return bitMatrix;
}
}
3. 调用方法:
/**
* 获取二维码
*/
@GetMapping(value="/getQRCodeImg",produces = "application/json;charset=utf-8")
public void getQRCodeImg(String qrCode, HttpServletResponse response){
// 生成二维码
BitMatrix qRcodeImg = QrCodeImageUtil.generateQRCodeStream(qrCode, response);
// 将二维码输出到页面中
try {
MatrixToImageWriter.writeToStream(qRcodeImg, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}