前言:
本文基于JAVA环境,以SpringBoot框架为基础开发。
正式开发步骤:
1、引入Maven依赖
<!--引入生成二维码的依赖-->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
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、测试
生成成功,可以扫码测试哟
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。