教你如何使用google.zxing結(jié)合springboot生成二維碼功能
我們使用兩種方式,去生成二維碼,但是其實(shí),二維碼的生成基礎(chǔ),都是zxing包,這是Google開(kāi)源的一個(gè)包,第一種是使用原始的zxing方式去實(shí)現(xiàn),第二種是使用hutool來(lái)實(shí)現(xiàn),hutool其實(shí)也是對(duì)于zxing的一個(gè)封裝,但是封裝前后,確實(shí)比較簡(jiǎn)單了。
Zxing原生方式
添加依賴(lài)
<!-- zxing生成二維碼 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>二維碼生成工具類(lèi)
下面是把生成二維碼的方法,封裝到了QRCodeUtil的類(lèi)之中,這個(gè)方法看起來(lái)還是比較多的,但是也談不上太復(fù)雜,主要是對(duì)于BufferedImage生成圖片,然后就是ImageIO.write()方法,write的位置,可以是普通的磁盤(pán)文件,也可以是web的流,我們使用web流的時(shí)候,就需要添加com.google.zxing-javase的依賴(lài)。
@Component
@Slf4j
public class QRCodeUtil {
/**
* CODE_WIDTH:二維碼寬度,單位像素
* CODE_HEIGHT:二維碼高度,單位像素
* FRONT_COLOR:二維碼前景色,0x000000 表示黑色
* BACKGROUND_COLOR:二維碼背景色,0xFFFFFF 表示白色
* 演示用 16 進(jìn)制表示,和前端頁(yè)面 CSS 的取色是一樣的,注意前后景顏色應(yīng)該對(duì)比明顯,如常見(jiàn)的黑白
*/
private static final int CODE_WIDTH = 400;
private static final int CODE_HEIGHT = 400;
private static final int FRONT_COLOR = 0x000000;
private static final int BACKGROUND_COLOR = 0xFFFFFF;
/**
* @param codeContent 二維碼參數(shù)內(nèi)容,如果是一個(gè)網(wǎng)頁(yè)地址,如 https://www.baidu.com/ 則 微信掃一掃會(huì)直接進(jìn)入此地址, 如果是一些參數(shù),如
* 1541656080837,則微信掃一掃會(huì)直接回顯這些參數(shù)值
* @param codeImgFileSaveDir 二維碼圖片保存的目錄,如 D:/codes
* @param fileName 二維碼圖片文件名稱(chēng),帶格式,如 123.png
*/
public static void createCodeToFile(String codeContent, File codeImgFileSaveDir, String fileName) {
try {
if (codeContent == null || "".equals(codeContent)) {
log.info("二維碼內(nèi)容為空,不進(jìn)行操作...");
return;
}
codeContent = codeContent.trim();
if (codeImgFileSaveDir == null || codeImgFileSaveDir.isFile()) {
codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory();
log.info("二維碼圖片存在目錄為空,默認(rèn)放在桌面...");
}
if (!codeImgFileSaveDir.exists()) {
codeImgFileSaveDir.mkdirs();
log.info("二維碼圖片存在目錄不存在,開(kāi)始創(chuàng)建...");
}
if (fileName == null || "".equals(fileName)) {
fileName = new Date().getTime() + ".png";
log.info("二維碼圖片文件名為空,隨機(jī)生成 png 格式圖片...");
}
BufferedImage bufferedImage = getBufferedImage(codeContent);
/*
* javax.imageio.ImageIO:java擴(kuò)展的圖像IO
* write(RenderedImage im, String formatName, File output)
* im:待寫(xiě)入的圖像, formatName:圖像寫(xiě)入的格式,output:寫(xiě)入的圖像文件,文件不存在時(shí)會(huì)自動(dòng)創(chuàng)建
*/
File codeImgFile = new File(codeImgFileSaveDir, fileName);
ImageIO.write(bufferedImage, "png", codeImgFile);
log.info("二維碼圖片生成成功:" + codeImgFile.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成二維碼并輸出到輸出流, 通常用于輸出到網(wǎng)頁(yè)上進(jìn)行顯示
* 輸出到網(wǎng)頁(yè)與輸出到磁盤(pán)上的文件中,區(qū)別在于最后一句 ImageIO.write
* write(RenderedImage im,String formatName,File output):寫(xiě)到文件中
* write(RenderedImage im,String formatName,OutputStream output):輸出到輸出流中
*
* @param codeContent :二維碼內(nèi)容
* @param outputStream :輸出流,比如 HttpServletResponse 的 getOutputStream
*/
public static void createCodeToOutputStream(String codeContent, OutputStream outputStream) {
try {
if (codeContent == null || "".equals(codeContent.trim())) {
log.info("二維碼內(nèi)容為空,不進(jìn)行操作...");
return;
}
codeContent = codeContent.trim();
BufferedImage bufferedImage = getBufferedImage(codeContent);
/*
* 區(qū)別就是以一句,輸出到輸出流中,如果第三個(gè)參數(shù)是 File,則輸出到文件中
*/
ImageIO.write(bufferedImage, "png", outputStream);
log.info("二維碼圖片生成到輸出流成功...");
} catch (Exception e) {
e.printStackTrace();
log.error("發(fā)生錯(cuò)誤: {}!", e.getMessage());
}
}
private static BufferedImage getBufferedImage(String codeContent) throws WriterException {
/*
* com.google.zxing.EncodeHintType:編碼提示類(lèi)型,枚舉類(lèi)型
* EncodeHintType.CHARACTER_SET:設(shè)置字符編碼類(lèi)型
* EncodeHintType.ERROR_CORRECTION:設(shè)置誤差校正
* ErrorCorrectionLevel:誤差校正等級(jí),L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
* 不設(shè)置時(shí),默認(rèn)為 L 等級(jí),等級(jí)不一樣,生成的圖案不同,但掃描的結(jié)果是一樣的
* EncodeHintType.MARGIN:設(shè)置二維碼邊距,單位像素,值越小,二維碼距離四周越近
*/
Map<EncodeHintType, Object> hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 1);
/*
* MultiFormatWriter:多格式寫(xiě)入,這是一個(gè)工廠(chǎng)類(lèi),里面重載了兩個(gè) encode 方法,用于寫(xiě)入條形碼或二維碼
* encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints)
* contents:條形碼/二維碼內(nèi)容
* format:編碼類(lèi)型,如 條形碼,二維碼 等
* width:碼的寬度
* height:碼的高度
* hints:碼內(nèi)容的編碼類(lèi)型
* BarcodeFormat:枚舉該程序包已知的條形碼格式,即創(chuàng)建何種碼,如 1 維的條形碼,2 維的二維碼 等
* BitMatrix:位(比特)矩陣或叫2D矩陣,也就是需要的二維碼
*/
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = multiFormatWriter.encode(codeContent, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
/*
* java.awt.image.BufferedImage:具有圖像數(shù)據(jù)的可訪(fǎng)問(wèn)緩沖圖像,實(shí)現(xiàn)了 RenderedImage 接口
* BitMatrix 的 get(int x, int y) 獲取比特矩陣內(nèi)容,指定位置有值,則返回true,將其設(shè)置為前景色,否則設(shè)置為背景色
* BufferedImage 的 setRGB(int x, int y, int rgb) 方法設(shè)置圖像像素
* x:像素位置的橫坐標(biāo),即列
* y:像素位置的縱坐標(biāo),即行
* rgb:像素的值,采用 16 進(jìn)制,如 0xFFFFFF 白色
*/
BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
for (int x = 0; x < CODE_WIDTH; x++) {
for (int y = 0; y < CODE_HEIGHT; y++) {
bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
}
}
return bufferedImage;
}
/**
* 根據(jù)本地二維碼圖片解析二維碼內(nèi)容 注:圖片必須是二維碼圖片,但也可以是微信用戶(hù)二維碼名片,上面有名稱(chēng)、頭像也是可以的)
*
* @param file 本地二維碼圖片文件,如 E:\\logs\\2.jpg
* @return
* @throws Exception
*/
public static String parseQRCodeByFile(File file) {
String resultStr = null;
if (file == null || file.isDirectory() || !file.exists()) {
return resultStr;
}
try {
/*
* ImageIO的BufferedImage read(URL input)方法用于讀取網(wǎng)絡(luò)圖片文件轉(zhuǎn)為內(nèi)存緩沖圖像
* 同理還有:read(File input)、read(InputStream input)、、read(ImageInputStream stream)
*/
BufferedImage bufferedImage = ImageIO.read(file);
/*
* com.google.zxing.client.j2se.BufferedImageLuminanceSource:緩沖圖像亮度源
* 將 java.awt.image.BufferedImage 轉(zhuǎn)為 zxing 的 緩沖圖像亮度源
* 關(guān)鍵就是下面這幾句:HybridBinarizer 用于讀取二維碼圖像數(shù)據(jù),BinaryBitmap 二進(jìn)制位圖
*/
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
/*
* 如果圖片不是二維碼圖片,則 decode 拋異常:com.google.zxing.NotFoundException
* MultiFormatWriter 的 encode 用于對(duì)內(nèi)容進(jìn)行編碼成 2D 矩陣
* MultiFormatReader 的 decode 用于讀取二進(jìn)制位圖數(shù)據(jù)
*/
Result result = new MultiFormatReader().decode(bitmap, hints);
resultStr = result.getText();
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
log.error("圖片非二維碼圖片, 路徑是: {}!", file.getPath());
}
return resultStr;
}
/**
* 根據(jù)網(wǎng)絡(luò)二維碼圖片解析二維碼內(nèi)容, 區(qū)別僅僅在于 ImageIO.read(url); 這一個(gè)重載的方法)
*
* @param url 二維碼圖片網(wǎng)絡(luò)地址,如 https://res.wx.qq.com/mpres/htmledition/images/mp_qrcode3a7b38.gif
* @return
* @throws Exception
*/
public static String parseQRCodeByUrl(URL url) {
String resultStr = null;
if (url == null) {
return resultStr;
}
try {
/*
* ImageIO 的 BufferedImage read(URL input) 方法用于讀取網(wǎng)絡(luò)圖片文件轉(zhuǎn)為內(nèi)存緩沖圖像
* 同理還有:read(File input)、read(InputStream input)、、read(ImageInputStream stream)
* 如果圖片網(wǎng)絡(luò)地址錯(cuò)誤,比如不能訪(fǎng)問(wèn),則 read 拋異常:javax.imageio.IIOException: Can't get input stream from URL!
*/
BufferedImage bufferedImage = ImageIO.read(url);
/*
* com.google.zxing.client.j2se.BufferedImageLuminanceSource:緩沖圖像亮度源
* 將 java.awt.image.BufferedImage 轉(zhuǎn)為 zxing 的 緩沖圖像亮度源
* 關(guān)鍵就是下面這幾句:HybridBinarizer 用于讀取二維碼圖像數(shù)據(jù),BinaryBitmap 二進(jìn)制位圖
*/
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable hints = new Hashtable();
/*
* 如果內(nèi)容包含中文,則解碼的字符集格式應(yīng)該和編碼時(shí)一致
*/
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
/*
* 如果圖片不是二維碼圖片,則 decode 拋異常:com.google.zxing.NotFoundException
* MultiFormatWriter 的 encode 用于對(duì)內(nèi)容進(jìn)行編碼成 2D 矩陣
* MultiFormatReader 的 decode 用于讀取二進(jìn)制位圖數(shù)據(jù)
*/
Result result = new MultiFormatReader().decode(bitmap, hints);
resultStr = result.getText();
} catch (IOException e) {
e.printStackTrace();
log.error("二維碼圖片地址錯(cuò)誤, 地址是: {}!", url);
} catch (NotFoundException e) {
e.printStackTrace();
log.error("圖片非二維碼圖片, 地址是: {}!", url);
}
return resultStr;
}添加Controller
public class QRCodeController {
@GetMapping("qrCode")
public void getQRCode(String codeContent, HttpServletResponse response) {
System.out.println("codeContent=" + codeContent);
try {
/*
* 調(diào)用工具類(lèi)生成二維碼并輸出到輸出流中
*/
QRCodeUtil.createCodeToOutputStream(codeContent, response.getOutputStream());
log.info("成功生成二維碼!");
} catch (IOException e) {
log.error("發(fā)生錯(cuò)誤, 錯(cuò)誤信息是:{}!", e.getMessage());
}
}
}添加測(cè)試頁(yè)面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>二維碼生成器</title>
<style type="text/css">
textarea {
font-size: 16px;
width: 300px;
height: 100px;
}
.hint {
color: red;
display: none;
}
.qrCodeDiv {
width: 200px;
height: 200px;
border: 2px solid sandybrown;
}
.qrCodeDiv img {
max-height: 100%;
max-width: 100%;
}
</style>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("button").click(function () {
var codeContent = $("textarea").val();
console.log(codeContent);
if (codeContent.trim() == "") {
$(".hint").text("二維碼內(nèi)容不能為空").fadeIn(500);
} else {
$(".hint").text("").fadeOut(500);
$("#codeImg").attr("src", "/qrCode?codeContent=" + codeContent);
}
});
});
</script>
</head>
<body>
<textarea placeholder="二維碼內(nèi)容..."></textarea><br>
<button>生成二維碼</button>
<span class="hint"></span>
<div class="qrCodeDiv">
<img src="" id="codeImg">
</div>
</body>
</html>Hutool的方式
Hutool的是非強(qiáng)制依賴(lài)性,因此zxing需要用戶(hù)自行引入,我們需要加入依賴(lài)。使用hutool的時(shí)候,com.google.zxing-javase的依賴(lài)可以不需要。
添加依賴(lài)
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>創(chuàng)建QRCodeService
QRCodeService其實(shí)就是對(duì)QrCodeUtil的功能的封裝,QrCodeUtil此處的類(lèi)是hutool工具提供的,和我們?cè)谏厦媾c自己與自己提供的QRCodeUtil類(lèi),不是同一個(gè),這個(gè)需要注意一下。QrCodeUtil的功能此處主要使用到了的是生成二維碼,到文件或者流之中,QrConfig是Hutool工具QrCodeUtil的配置類(lèi)。
@Service
@Slf4j
public class QRCodeService {
// 自定義參數(shù),這部分是Hutool工具封裝的
private static QrConfig initQrConfig() {
QrConfig config = new QrConfig(300, 300);
// 設(shè)置邊距,既二維碼和背景之間的邊距
config.setMargin(3);
// 設(shè)置前景色,既二維碼顏色(青色)
config.setForeColor(Color.CYAN.getRGB());
// 設(shè)置背景色(灰色)
config.setBackColor(Color.GRAY.getRGB());
return config;
}
/**
* 生成到文件
*
* @param content
* @param filepath
*/
public void createQRCode2File(String content, String filepath) {
try {
QrCodeUtil.generate(content, initQrConfig(), FileUtil.file(filepath));
log.info("生成二維碼成功, 位置在:{}!", filepath);
} catch (QrCodeException e) {
log.error("發(fā)生錯(cuò)誤! {}!", e.getMessage());
}
}
/**
* 生成到流
*
* @param content
* @param response
*/
public void createQRCode2Stream(String content, HttpServletResponse response) {
try {
QrCodeUtil.generate(content, initQrConfig(), "png", response.getOutputStream());
log.info("生成二維碼成功!");
} catch (QrCodeException | IOException e) {
log.error("發(fā)生錯(cuò)誤! {}!", e.getMessage());
}
}
}添加Controller
@RestController
@Slf4j
public class QRCodeController {
@Autowired
private QRCodeService qrCodeService;
@GetMapping("qrCode")
public void getQRCode(String codeContent, HttpServletResponse response) {
try {
qrCodeService.createQRCode2Stream(codeContent, response);
log.info("成功生成二維碼!");
} catch (Exception e) {
log.error("發(fā)生錯(cuò)誤, 錯(cuò)誤信息是:{}!", e.getMessage());
}
}
}效果測(cè)試
我們使用的頁(yè)面和上述相同,所以,頁(yè)面的情況是一樣的,效果展示如下:

到此這篇關(guān)于使用google.zxing結(jié)合springboot生成二維碼功能的文章就介紹到這了,更多相關(guān)springboot生成二維碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
線(xiàn)程池中使用spring aop事務(wù)增強(qiáng)
這篇文章主要介紹了線(xiàn)程池中使用spring aop事務(wù)增強(qiáng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
java中synchronized Lock(本地同步)鎖的8種情況
jmeter添加自定義擴(kuò)展函數(shù)之圖片base64編碼示例詳解
淺談Spring裝配Bean之組件掃描和自動(dòng)裝配
MyBatis-Plus結(jié)合Layui實(shí)現(xiàn)分頁(yè)方法
java中staticclass靜態(tài)類(lèi)詳解

