Hutool工具类生成二维码
1、引入依赖
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>
2、编写controller
1、带头像的二维码
//浏览器直接显示二维码图片@GetMapping("/download3")public void download3(HttpServletResponse response) throws Exception {QrConfig config = new QrConfig(600, 600);// 设置边距,既二维码和背景之间的边距config.setMargin(1);// 设置前景色,二维码颜色(绿色)config.setForeColor(new Color(0, 139, 69));// 设置背景色(淡黄色)config.setBackColor(new Color(255, 255, 224));// 设置中间的 logo 图片String logoPath = ResourceUtils.getFile("classpath:logo/1.jpg").getPath();config.setImg(logoPath);// 设置容错级别config.setErrorCorrection(ErrorCorrectionLevel.H);byte[] pngArr = QrCodeUtil.generatePng("http://www.baidu.com", config);response.setContentType("image/png");response.getOutputStream().write(pngArr, 0, pngArr.length);}
2、带文字的二维码
//浏览器直接显示二维码图片@GetMapping("/download3")public void download3(HttpServletResponse response) throws Exception {// 创建 QR 配置QrConfig config = new QrConfig(400, 400);config.setMargin(1);config.setForeColor(new Color(0, 139, 69));config.setBackColor(new Color(255, 255, 224));config.setErrorCorrection(ErrorCorrectionLevel.H);// 生成二维码图像BufferedImage qrImage = QrCodeUtil.generate("http://www.baidu.com", config);// 在二维码上绘制文本Graphics2D g2d = qrImage.createGraphics();g2d.setFont(new Font("微软雅黑", Font.PLAIN, 40));g2d.setColor(new Color(255, 140, 0));// 计算文本的宽高,确保居中FontMetrics metrics = g2d.getFontMetrics();int textWidth = metrics.stringWidth("张三李四王五张三李四王五");int textHeight = metrics.getHeight();// 绘制文本g2d.drawString("张三李四王五张三李四王五", (qrImage.getWidth() - textWidth) / 2, (qrImage.getHeight() + textHeight) / 2);g2d.dispose();// 输出二维码图片到响应response.setContentType("image/png");OutputStream os = response.getOutputStream();ImageIO.write(qrImage, "PNG", os);}
1、效果