基于Springboot+Hutool工具类实现生成二维码
Springboot版本2.6
1.引入Hutool依赖
<!--开发工具集-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.10</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
2.添加配置类QrConfig
@Configuration
public class QrCodeConfig {
@Bean
public QrConfig qrConfig(){
//初始宽度和高度
QrConfig qrConfig = new QrConfig();
//设置边距,即二维码和边框的距离
qrConfig.setMargin(1);
//设置前景色
qrConfig.setForeColor(Color.black.getRGB());
//设置背景色
qrConfig.setBackColor(Color.WHITE.getRGB());
// 高纠错级别
qrConfig.setErrorCorrection(ErrorCorrectionLevel.H);
return qrConfig;
}
}
3.添加工具类QrUtils
@Component
public class QrUtils {
@Autowired
private QrConfig config;
/**
* 生成文件
* @param content
*/
public void createCodeToFile(String content, HttpServletResponse response) {
try {
BufferedImage bufferedImage = QrCodeUtil.generate(content,config);
try {
//以JPEG格式向客户端发送也可以更改为PNG
ServletOutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "JPEG", os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (QrCodeException e) {
e.printStackTrace();
}
}
/**
* 生成到流
*/
public void createQRCode2Stream(String content, HttpServletResponse response) {
try {
QrCodeUtil.generate(content, config, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}
调用接口
@GetMapping("/createQrCode")
public void createQrCode(@RequestParam String url, HttpServletResponse response){
//在图片上生成二维码,图片宽高都为200px
qrUtils.createCodeToFile(url,response);
}
以文件流的形式返回给前端 这里用Vue做前端
const getQrCode = async () => {
const url = window.location.href
const res:any = await api.getQrCode(url);
QrCodeUrl.value = URL.createObjectURL(res);
}