研究一下二維碼的生成吧!
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 先測試生成圖檔的請求
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yY3MjN1YTNkJWM2IGM3EGN5EDN0cjM4cDOhRmN4QDOk9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
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/