文檔地址
https://hutool.cn/docs/#/extra/%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%B7%A5%E5%85%B7-QrCodeUtil
pom引入
hutool jar
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.0.7</version>
</dependency>
考慮到Hutool的非強制依賴性,因此zxing需要用戶自行引入
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
編譯需要
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
後端代碼
/**
* 生成二維碼
* @param content 內容
* @param logourl logo
*/
public void createQrCodeN(String content, String logourl, int width, int height,HttpServletResponse response){
QrConfig config = new QrConfig(width, height);
File file = null;
try {
file = ResourceUtils.getFile(logourl);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//附帶logo
config.setImg(file);
// 設置邊距,既二維碼和背景之間的邊距
config.setMargin(3);
// 高糾錯級別
config.setErrorCorrection(ErrorCorrectionLevel.H);
// 設置前景色,既二維碼顏色(青色)
config.setForeColor(new Color(0,60,130).getRGB());
// 設置背景色(灰色)
config.setBackColor(new Color(242,242,242).getRGB());
/* try {
OutputStream out = new FileOutputStream("");
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
BufferedImage bufferedImage = QrCodeUtil.generate(//
content, //二維碼內容
config
);
try {
//以JPEG格式向客戶端發送
ServletOutputStream os = response.getOutputStream();
ImageIO.write(bufferedImage, "PNG",os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
controller
postman測試
如果打成jar需要這樣讀取file
InputStream initialStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(logourl);
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File file = new File("src/main/resources/targetFile.tmp");