钻研一下二维码的生成吧!
1. 新建 spring boot 我的项目
1.1 pom.xml
<!-- 生成二维码依赖 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
1.2 新建生成二维码工具类
/**
* 生成二维码工具类
*
* @author zhouzhaodong
*/
public class QRCodeGenerator {
/**
* 生成二维码图片
* @param text
* @param width
* @param height
* @param filePath
* @throws WriterException
* @throws IOException
*/
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
/**
* 生成二维码流
* @param text
* @param width
* @param height
* @return
*/
public static String writeToStream(String text, int width, int height) {
String message = "";
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix;
try {bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
Base64.Encoder encoder = Base64.getEncoder();
message = encoder.encodeToString(outputStream.toByteArray());
} catch (Exception e) {e.printStackTrace();
}
return message;
}
}
1.3 新建 controller
/**
* 生成二维码
* @author zhouzhaodong
*/
@RestController
public class QRCodeController {
/**
* 生成二维码图片并将地址回传给前端
* @param orderNo
* @return
*/
@RequestMapping("/qrcode/image")
public String qrcodeImage(String orderNo) {
String failPath = "src/main/resources/png/" + orderNo + ".png";
try {QRCodeGenerator.generateQRCodeImage(orderNo, 350, 350, failPath);
} catch (Exception e) {e.printStackTrace();
}
return failPath;
}
/**
* 生成二维码 Base64 回传给前端
* @param orderNo
* @return
*/
@RequestMapping("/qrcode/base64")
public String qrcodeBase64(String orderNo) {
String message = "";
try {message = QRCodeGenerator.writeToStream(orderNo, 350, 350);
} catch (Exception e) {e.printStackTrace();
}
return message;
}
}
1.4 测试
这里我应用 IDEA 自带的 HTTP 申请客户端进行测试。
1.4.1 先测试生成图片的申请
1.4.2 再测试生成 Base64 的申请
能够去 https://tool.jisuapi.com/base642pic.html 去将 Base64 转为图片
源代码地址:
https://github.com/zhouzhaodong/springboot/tree/master/spring-boot-qrcode
集体博客地址:
http://www.zhouzhaodong.xyz/