什么是Zxing
ZXing,一個支持在圖像中解碼和生成條形碼(如二維碼、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的庫。ZXing(“zebra crossing”)是一個開源的、多格式的、用Java實現(xiàn)的一維/二維條碼圖像處理庫,具有到其他語言的端口。
具體實現(xiàn)
對于在Spring項目中使用Zxing生成二維碼,其實比較簡單,只需要引入依賴,然后調(diào)用方法,并傳入需要的參數(shù)即可。
最核心的代碼就是QRCodeWriter qrCodeWriter=new QRCodeWriter(); bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
text :二維碼中攜帶的內(nèi)容
BarcodeFormat.QR_CODE :是一個枚舉值,表示二維碼(Quick Response Code)格式
width: 寬
height: 高
hints: 是一個map,包含一些其他的設(shè)置內(nèi)容
1. 在pom文件中導(dǎo)入依賴
<!-- ZXing二維碼 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
2. 二維碼生成工具類
生成的二維碼可以輸出到本地文件中,也可以直接以IO流的形式返回給前端,前端再進(jìn)行二維碼的顯示。
package com.lixy.sharingcurriculum.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
public class QRCodeGenerator {
/**
* 生成二維碼輸出文件
* @param text
* @throws WriterException
* @throws IOException
*/
public static void generateQRCodeImage(String text) throws WriterException, IOException {
int width = 350;
int height = 350;
String filePath = "C:/Users/li/Pictures/qrtest.png";
// 定義二維碼的參數(shù)
HashMap<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); 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);
}
/**
* 生成二維碼并以IO流返回
* @param text
* @return
* @throws WriterException
*/
public static BitMatrix createQRCode(String text) throws IOException {
int width=200;
int height=200;
HashMap<EncodeHintType,Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8"); //指定字符編碼為“utf-8”
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); //指定二維碼的糾錯等級為中級
hints.put(EncodeHintType.MARGIN, 2); //設(shè)置圖片的邊距,單位像素,非負(fù)值
BitMatrix bitMatrix=null;
try{
QRCodeWriter qrCodeWriter=new QRCodeWriter();
bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
}catch (WriterException e){
e.printStackTrace();
}
return bitMatrix;
}
public static void main(String[] args) {
try {
generateQRCodeImage("code");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 控制層和服務(wù)層
/**
* 生成帶有課程表信息的二維碼
*/
@PostMapping("/generateQRCode")
public void generateQRCode(String scheduleid,HttpServletResponse response) throws IOException {
//設(shè)置響應(yīng)流信息
response.setContentType("image/png");
//沒有緩存
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
//設(shè)置過期的時間戳,為0表示立即過期
response.setDateHeader("Expire", 0);
BitMatrix bitMatrix=scheduleService.generateQRCode(scheduleid);
OutputStream stream=response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"png",stream);
}
/**
* 生成帶有課程表信息的二維碼
* @return
*/
@Override
public BitMatrix generateQRCode(String scheduleid) throws IOException {
Schedule schedule=scheduleMapper.selectById(scheduleid);
//將課表信息轉(zhuǎn)換為json格式
String scheduleJson= JSON.toJSONString(schedule);
return QRCodeGenerator.createQRCode(scheduleJson);
}
4. 前端
wx.request({
url: 'http://localhost:8080/schedule/generateQRCode?scheduleid='+this.data.id,
method:'POST',
responseType: 'arraybuffer', // 指定返回類型為ArrayBuffer
success:res=>{
const base64=wx.arrayBufferToBase64(res.data);
const imagesrc='data:image/png;base64,'+base64;
console.log("二維碼url:"+imagesrc)
this.setData({
qrCodeImg:imagesrc
})
}
})
<view>
掃描二維碼即可導(dǎo)入課表
</view>
<image src="{{qrCodeImg}}" mode="aspectFit"/>
總結(jié)
另外還可以使用一些其他的方式生成二維碼,比如基于開源的Hutool工具生成二維碼,可以參考SpringBoot系列(22):Java生成二維碼的幾種實現(xiàn)方式(基于Spring Boot)
也可以直接使用js生成,有QRCode.js庫可以直接引用。文章來源:http://www.zghlxwxcb.cn/news/detail-850917.html
參考
使用Zxing生成二維碼
Java生成二維碼并以IO流的形式返回給前端展示(不需寫入服務(wù)器),以及下載二維碼圖片文章來源地址http://www.zghlxwxcb.cn/news/detail-850917.html
到了這里,關(guān)于SpringBoot使用Zxing生成二維碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!