作者:wcnm | 来源:互联网 | 2023-01-29 19:45
前言:本文基于JAVA环境,以SpringBoot框架为根底开发。正式开发步骤:1、引入Maven依赖{代码}2、创立生成二维码工具类QRCodeGenerator.java{代码}
前言:
本文基于JAVA环境,以SpringBoot框架为根底开发。
正式开发步骤:
1、引入Maven依赖
com.google.zxing
core
3.3.0
com.google.zxing
javase
3.3.0
2、创立生成二维码工具类QRCodeGenerator.java
/**
* Java生成二维码
* @date: 2022/6/16 21:21
* @author: gxw
*/
public class QRCodeGenerator {
//生成的二维码的门路
private static String QR_CODE_IMAGE_PATH = PropertiesValues.getPropertiesValue("wx.pay.img.generator_path", "application.properties");
//正式上线前缀
private static String PAY_PREFIX = PropertiesValues.getPropertiesValue("wx.pay.img.prefix", "application.properties");
//二维码图片的宽度
private static int WIDTH = 500;
//二维码图片的高度
private static int HEIGHT = 500;
public static String generateQRCodeImage(String content) throws Exception {
QR_CODE_IMAGE_PATH = PropertiesValues.getPropertiesValue("wx.pay.img.generator_path", "application.properties");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//H最高容错等级
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT,hints);
String imgName = RandomUtils.generateRandomString(6) + ".png";
QR_CODE_IMAGE_PATH += imgName;
File file = new File(QR_CODE_IMAGE_PATH);
if(!file.exists()){
file.mkdirs();
}
Path path = FileSystems.getDefault().getPath(QR_CODE_IMAGE_PATH);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
return PAY_PREFIX + imgName;
}
}
3、测试
生成胜利,能够扫码测试哟