方案一
借助 hutool 工具
引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
注意如果生成内容是中文的 使用微信扫码不显示内容,需要复制后自行查询内容,如果内容简单 生成的二维码就简介稀疏,如内容比较多 二维码就比较稠密
public static void main(String[] args) {
// 设置二维码的内容
String content = "生成二维码";
// 设置二维码的配置
QrConfig config = new QrConfig(300, 300);
config.setErrorCorrection(ErrorCorrectionLevel.M); // 设置纠错级别
// 生成二维码并保存到文件
QrCodeUtil.generate(content, config, FileUtil.file("E:/qrcode.png"));
// 或者直接输出到流
// QrCodeUtil.generate(content, config, System.out);
}
方案二
引入依赖 借助谷歌组件 google.zxing
注意如果生成内容是中文的 使用微信扫码不显示内容,需要复制后自行查询内容,如果内容简单 生成的二维码就简介稀疏,如内容比较多 二维码就比较稠密
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
@GetMapping("generateQRCode")
public void generateQRCode(@RequestParam("id") Long id, HttpServletResponse response) {
try {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
String content = "生成二维码";
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode( content , BarcodeFormat.QR_CODE, 200, 200, hints);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
response.setContentType("image/png");
response.getOutputStream().write(byteArrayOutputStream.toByteArray());
response.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
}
}