SpringBoot生成二維碼的實現(xiàn)
更新時間:2020年12月08日 08:54:30 作者:瑞 新
這篇文章主要介紹了SpringBoot生成二維碼的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
效果圖

步驟
maven依賴
<!-- 生成二維碼-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
工具類
package com.bennyrhys.mall.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
/**
* 描述: 生成二維碼工具
*/
public class QRCodeGenerator {
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);
}
public static void main(String[] args) {
try {
generateQRCodeImage("Hello World", 350, 350, "E:/JAVA/mall/src/main/resources/images/QRTest.png");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
service
/**
* 生成二維碼
* 圖片可解析出訪問的支付對應訂單號的支付連接
* @param orderNo 訂單號
* @return 返回圖片地址
*/
@Override
public String qrcode(String orderNo) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String address = ip + ":" + request.getLocalPort();
String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
try {
QRCodeGenerator.generateQRCodeImage(payUrl, 350, 350, Constant.FILE_UPLOAD_PATH + orderNo + ".png");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String pngAddress = "http://" + address + "/images-dev/" + orderNo + ".png";
return pngAddress;
}
擴展
局域網(wǎng)調試

線上調試
切換ip
# 指定IP(防止ip轉發(fā)獲取的是內網(wǎng)ip) file.upload.ip=127.0.0.1
到此這篇關于SpringBoot生成二維碼的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot生成二維碼內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot+Mybatis項目使用Redis做Mybatis的二級緩存的方法
本篇文章主要介紹了SpringBoot+Mybatis項目使用Redis做Mybatis的二級緩存的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
詳解Java如何在CompletableFuture中實現(xiàn)日志記錄
這篇文章主要為大家詳細介紹了一種slf4j自帶的MDC類,來記錄完整的請求日志,和在CompletableFuture異步線程中如何保留鏈路id,需要的可以參考一下2023-04-04

