首先,导包
<!--二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
编写工具类
public class QRCodeUtil
{
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, 0);
BitMatrix bitMatrix;
try {
//参数分别为:编码内容、编码类型、图片宽度、图片高度,设置参数
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 350, 350,hints);
}catch(WriterException e) {
e.printStackTrace();
return null;
}
return bitMatrix;
}
public static byte[] qr_code(String code_url, HttpServletResponse response)
{
try {
BitMatrix qRcodeImg = generateQRCodeStream(code_url, response);
// 将二维码输出到页面中
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(qRcodeImg, "png", pngOutputStream);
return pngOutputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return new byte[]{};
}
}
public static String genCode(String url, HttpServletResponse response)
{
Base64.Encoder encoder1 = Base64.getEncoder();
String qrCodeImage = "data:image/jpeg;base64," + encoder1.encodeToString(qr_code(url, response));
URLEncoder.encode(qrCodeImage, "UTF-8");
return qrCodeImage;
}
}
调用genCode方法返回字符串,将字符串放到<img src=''>里面就可以