Java Spring boot 二维码生成

<!--生成二维码的功能Google的Zxing包-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>

下面是代码
/**
* @param text 二维码文件内容
* @param width 生成二维码的宽度
* @param height 生成二维码的高度
* @param filePath 生成二维码的路径
* @throws WriterException
* @throws IOException
*/
public static String generateQRCodeImage(String text, int width, int height, String filePath) {
try {
Map hints = new HashMap();
//设置UTF-8, 防止中文乱码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//设置二维码四周白色区域的大小
hints.put(EncodeHintType.MARGIN, 0);
//设置二维码的容错性
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
} catch (Exception e) {
log.error(e.getMessage());
}
return filePath;
}

mian方法也可以使用
posted @ 2021-08-30 10:38  未来可期,奔向未来  阅读(113)  评论(0)    收藏  举报