谷歌二維碼引擎com.google.zxing二維碼生成與解析
Google ZXing 概述與下載
1、Java 操作二維碼的開源項(xiàng)目很多,如 SwetakeQRCode、BarCode4j、Zxing 等等
2、本文將介紹簡(jiǎn)單易用的 google 公司的 zxing,zxing 使用方便,可以操作條形碼或者二維碼等,不僅有 java 版本,還有 Android 版。
GitHub 開源地址: https://github.com/zxing/zxing
zxing 二進(jìn)制包下載地址:https://repo1.maven.org/maven2/com/google/zxing
zxing Maven 倉庫地址:https://mvnrepository.com/artifact/com.google.zxing
二進(jìn)制包下載
1、進(jìn)入 zxing 二進(jìn)制包下載地址:https://repo1.maven.org/maven2/com/google/zxing,如下所示:
2、zxing/core 是二維碼操作的核心包,必須使用;zxing/javase 是對(duì) Java Web 應(yīng)用的拓展。點(diǎn)擊鏈接進(jìn)入,選擇相應(yīng)的版本,然后下載即可,如下所示下載的是 3.3.3 版。
3、開發(fā)中如果是非 web 應(yīng)用則導(dǎo)入 core 包即可,如果是 web 應(yīng)用,則 core 與 javase 一起導(dǎo)入。
Maven 依賴
<!--如果是非 web 應(yīng)用則導(dǎo)入 core 包即可,如果是 web 應(yīng)用,則 core 與 javase 一起導(dǎo)入。--> <!-- https://mvnrepository.com/artifact/com.google.zxing/core --> <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>
保存二維碼圖片
1、需求是將參數(shù)生成到二維碼中,然后將二維碼保存到磁盤上的圖片文件中。
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import javax.swing.filechooser.FileSystemView; import java.awt.image.BufferedImage; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2018/11/8 0008. * 二維碼、條形碼工具類 */ public class QRBarCodeUtil { /** * CODE_WIDTH:二維碼寬度,單位像素 * CODE_HEIGHT:二維碼高度,單位像素 * FRONT_COLOR:二維碼前景色,0x000000 表示黑色 * BACKGROUND_COLOR:二維碼背景色,0xFFFFFF 表示白色 * 演示用 16 進(jìn)制表示,和前端頁面 CSS 的取色是一樣的,注意前后景顏色應(yīng)該對(duì)比明顯,如常見的黑白 */ 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; public static void main(String[] args) { String codeContent1 = "https://www.baidu.com/"; createCodeToFile(codeContent1, null, null); String codeContent2 = "4c86fed8-7ac9-4db7-956e-6cfe84268059"; createCodeToFile(codeContent2, null, null); } /** * 生成二維碼 并 保存為圖片 */ /** * @param codeContent :二維碼參數(shù)內(nèi)容,如果是一個(gè)網(wǎng)頁地址,如 https://www.baidu.com/ 則 微信掃一掃會(huì)直接進(jìn)入此地址 * 如果是一些參數(shù),如 1541656080837,則微信掃一掃會(huì)直接回顯這些參數(shù)值 * @param codeImgFileSaveDir :二維碼圖片保存的目錄,如 D:/codes * @param fileName :二維碼圖片文件名稱,帶格式,如 123.png */ public static void createCodeToFile(String codeContent, File codeImgFileSaveDir, String fileName) { try { /** 參數(shù)檢驗(yàn)*/ if (codeContent == null || "".equals(codeContent)) { System.out.println("二維碼內(nèi)容為空,不進(jìn)行操作..."); return; } codeContent = codeContent.trim(); if (codeImgFileSaveDir == null || codeImgFileSaveDir.isFile()) { codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory(); System.out.println("二維碼圖片存在目錄為空,默認(rèn)放在桌面..."); } if (!codeImgFileSaveDir.exists()) { codeImgFileSaveDir.mkdirs(); System.out.println("二維碼圖片存在目錄不存在,開始創(chuàng)建..."); } if (fileName == null || "".equals(fileName)) { fileName = new Date().getTime() + ".png"; System.out.println("二維碼圖片文件名為空,隨機(jī)生成 png 格式圖片..."); } /**com.google.zxing.EncodeHintType:編碼提示類型,枚舉類型 * EncodeHintType.CHARACTER_SET:設(shè)置字符編碼類型 * 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:多格式寫入,這是一個(gè)工廠類,里面重載了兩個(gè) encode 方法,用于寫入條形碼或二維碼 * encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints) * contents:條形碼/二維碼內(nèi)容 * format:編碼類型,如 條形碼,二維碼 等 * width:碼的寬度 * height:碼的高度 * hints:碼內(nè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ù)的可訪問緩沖圖像,實(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); } } /**javax.imageio.ImageIO java 擴(kuò)展的圖像IO * write(RenderedImage im,String formatName,File output) * im:待寫入的圖像 * formatName:圖像寫入的格式 * output:寫入的圖像文件,文件不存在時(shí)會(huì)自動(dòng)創(chuàng)建 * * 即將保存的二維碼圖片文件*/ File codeImgFile = new File(codeImgFileSaveDir, fileName); ImageIO.write(bufferedImage, "png", codeImgFile); System.out.println("二維碼圖片生成成功:" + codeImgFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } }
程序運(yùn)行之后,控制臺(tái)輸出:
二維碼圖片存在目錄為空,默認(rèn)放在桌面...
二維碼圖片文件名為空,隨機(jī)生成 png 格式圖片...
二維碼圖片生成成功:C:\Users\Administrator.SC-201707281232\Desktop\1541657067852.png
二維碼圖片存在目錄為空,默認(rèn)放在桌面...
二維碼圖片文件名為空,隨機(jī)生成 png 格式圖片...
二維碼圖片生成成功:C:\Users\Administrator.SC-201707281232\Desktop\1541657067992.png
桌面上已經(jīng)生成成功,左邊是百度地址二維碼,右邊是一串隨機(jī)的 UUID,可以使用微信掃一掃進(jìn)行掃描。如下所示,對(duì)于網(wǎng)頁地址掃,微信描后直接進(jìn)入了,對(duì)于隨機(jī)碼則回顯。
總結(jié):從代碼中可以看出,zxing 核心的代碼其實(shí)就是幾行,重點(diǎn)就是生成 2D 矩陣 BitMatrix,后面的 BufferedImage、ImageIO 這些都是 Java JDK 原生的 API。
在線生成二維碼
項(xiàng)目中很多時(shí)候二維碼都是根據(jù)參數(shù)實(shí)時(shí)輸出到網(wǎng)頁上進(jìn)行顯示的,它的實(shí)現(xiàn)原理完全類似驗(yàn)證碼,如下所示,它們都是后臺(tái)先生成內(nèi)存圖像 BufferedImage ,然后使用 ImageIO.write 寫出來。
現(xiàn)在來開始實(shí)現(xiàn)在線生成二維碼的功能,因?yàn)檫@里需要用到前后臺(tái)交互,所以只貼出關(guān)鍵代碼,無論是使用原始的 Servlet ,還是 SpringMVC,總之原理都是使用 ImageIO.write 將 內(nèi)存圖像 BufferedImage 寫到 HttpServletResponse getOutputStream 的輸出流中。
二維碼參數(shù)內(nèi)容中文也是可以的,但是建議非中文。
前端頁面
為了簡(jiǎn)單,使用了 spring boot 構(gòu)建項(xiàng)目,前端頁面使用 html,對(duì)于使用 jsp 頁面也是同理,頁面內(nèi)容基本一致。
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> <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); /** * 如果輸出的內(nèi)容為空,則提示,否則改變 img 的地址重新生成 二維碼 */ if (codeContent.trim() == "") { $(".hint").text("二維碼內(nèi)容不能為空").fadeIn(500); } else { $(".hint").text("").fadeOut(500); /**coco 是應(yīng)用名稱,qrCode 是后臺(tái)訪問路徑,codeContent 是后臺(tái)控制層接收的參數(shù)*/ $("#codeImg").attr("src", "/coco/qrCode?codeContent=" + codeContent); } }); }); </script> </head> <body> <textarea placeholder="二維碼內(nèi)容..."></textarea><br> <button>生成二維碼</button> <span class="hint"></span> <!--二維碼顯示曲,與驗(yàn)證碼一樣,直接使用 img 標(biāo)簽請(qǐng)求即可--> <!--下面是 thymeleaf 的寫法,qrCode 是后臺(tái)訪問的路徑, codeContent 是 get 請(qǐng)求攜帶的參數(shù),值為 "謝謝"--> <!--如果是純 html 或者 jsp 寫法,則可以用:<img src="/coco/qrCode?codeContent=謝謝" id="codeImg">,coco 是應(yīng)用名稱--> <div class="qrCodeDiv"> <img src="" th:src="@{/qrCode(codeContent=謝謝)}" id="codeImg"> </div> </body> </html>
img 標(biāo)簽訪問的后臺(tái)方法如下,使用的是 spring mvc,即便是 servlet 也是同理:
import com.lct.utils.QRBarCodeUtil; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by Administrator on 2018/11/8 0008. * 系統(tǒng)控制器層 */ @Controller public class SystemController { @GetMapping("qrCode") public void getQRCode(String codeContent, HttpServletResponse response) { System.out.println("codeContent=" + codeContent); try { /** * 調(diào)用工具類生成二維碼并輸出到輸出流中 */ QRBarCodeUtil.createCodeToOutputStream(codeContent, response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } }
控制層調(diào)用的二維碼工具類方法如下:
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import sun.net.www.content.image.png; import javax.imageio.ImageIO; import javax.swing.filechooser.FileSystemView; import java.awt.image.BufferedImage; import java.io.File; import java.io.OutputStream; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2018/11/8 0008. * 二維碼、條形碼工具類 */ public class QRBarCodeUtil { /** * CODE_WIDTH:二維碼寬度,單位像素 * CODE_HEIGHT:二維碼高度,單位像素 * FRONT_COLOR:二維碼前景色,0x000000 表示黑色 * BACKGROUND_COLOR:二維碼背景色,0xFFFFFF 表示白色 * 演示用 16 進(jìn)制表示,和前端頁面 CSS 的取色是一樣的,注意前后景顏色應(yīng)該對(duì)比明顯,如常見的黑白 */ 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; /** * 生成二維碼 并 輸出到輸出流————通常用于輸出到網(wǎng)頁上進(jìn)行顯示 * 輸出到網(wǎng)頁與輸出到磁盤上的文件中,區(qū)別在于最后一句 ImageIO.write * write(RenderedImage im,String formatName,File output):寫到文件中 * write(RenderedImage im,String formatName,OutputStream output):輸出到輸出流中 * * @param codeContent :二維碼內(nèi)容 * @param outputStream :輸出流,比如 HttpServletResponse 的 getOutputStream */ public static void createCodeToOutputStream(String codeContent, OutputStream outputStream) { try { /** 參數(shù)檢驗(yàn)*/ if (codeContent == null || "".equals(codeContent.trim())) { System.out.println("二維碼內(nèi)容為空,不進(jìn)行操作..."); return; } codeContent = codeContent.trim(); /**com.google.zxing.EncodeHintType:編碼提示類型,枚舉類型 * EncodeHintType.CHARACTER_SET:設(shè)置字符編碼類型 * 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:多格式寫入,這是一個(gè)工廠類,里面重載了兩個(gè) encode 方法,用于寫入條形碼或二維碼 * encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints) * contents:條形碼/二維碼內(nèi)容 * format:編碼類型,如 條形碼,二維碼 等 * width:碼的寬度 * height:碼的高度 * hints:碼內(nè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ù)的可訪問緩沖圖像,實(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); } } /** * 區(qū)別就是以一句,輸出到輸出流中,如果第三個(gè)參數(shù)是 File,則輸出到文件中 */ ImageIO.write(bufferedImage, "png", outputStream); System.out.println("二維碼圖片生成到輸出流成功..."); } catch (Exception e) { e.printStackTrace(); } } }
至此編碼接收,核心就是后臺(tái)將圖像輸出到輸出流,頁面上使用 img 標(biāo)簽顯示即可,當(dāng)然也可以使用 a 標(biāo)簽或者在瀏覽器地址欄上直接訪問。
解析二維碼圖片
對(duì)于二維碼圖片也可以反過來解析出它的參數(shù)內(nèi)容,編碼也很簡(jiǎn)單,基本就是反過來。
import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import javax.swing.filechooser.FileSystemView; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * Created by Administrator on 2018/11/8 0008. * 二維碼、條形碼工具類 */ public class QRBarCodeUtil { /** * CODE_WIDTH:二維碼寬度,單位像素 * CODE_HEIGHT:二維碼高度,單位像素 * FRONT_COLOR:二維碼前景色,0x000000 表示黑色 * BACKGROUND_COLOR:二維碼背景色,0xFFFFFF 表示白色 * 演示用 16 進(jìn)制表示,和前端頁面 CSS 的取色是一樣的,注意前后景顏色應(yīng)該對(duì)比明顯,如常見的黑白 */ 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; /** * 根據(jù)本地二維碼圖片————————解析二維碼內(nèi)容 * (注:圖片必須是二維碼圖片,但也可以是微信用戶二維碼名片,上面有名稱、頭像也是可以的) * * @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(); System.out.println("-----圖片非二維碼圖片:" + 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ò)誤,比如不能訪問,則 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(); System.out.println("-----二維碼圖片地址錯(cuò)誤:" + url); } catch (NotFoundException e) { e.printStackTrace(); System.out.println("-----圖片非二維碼圖片:" + url); } return resultStr; } public static void main(String[] args) throws MalformedURLException { File localFile = new File("E:\\logs\\1.png"); String localQRcodeContent = parseQRCodeByFile(localFile); System.out.println(localFile + " 二維碼內(nèi)容:" + localQRcodeContent); URL url = new URL("https://res.wx.qq.com/mpres/htmledition/images/mp_qrcode3a7b38.gif"); String netQRcodeContent = parseQRCodeByUrl(url); System.out.println(url + " 二維碼內(nèi)容:" + netQRcodeContent); } }
控制臺(tái)輸出:
E:\logs\1.png 二維碼內(nèi)容:wmx1993328
https://res.wx.qq.com/mpres/htmledition/images/mp_qrcode3a7b38.gif 二維碼內(nèi)容:http://weixin.qq.com/r/RHU6NQjE1japhxlWnyBg
親測(cè)結(jié)果完全正確,即便是如下形式的二維碼名片也能解析成功(為了不泄露信息,其中的紅色圓圈是后期加上的)
工具類完整內(nèi)容
import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import javax.swing.filechooser.FileSystemView; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * Created by Administrator on 2018/11/8 0008. * 二維碼、條形碼工具類 */ public class QRBarCodeUtil { /** * CODE_WIDTH:二維碼寬度,單位像素 * CODE_HEIGHT:二維碼高度,單位像素 * FRONT_COLOR:二維碼前景色,0x000000 表示黑色 * BACKGROUND_COLOR:二維碼背景色,0xFFFFFF 表示白色 * 演示用 16 進(jìn)制表示,和前端頁面 CSS 的取色是一樣的,注意前后景顏色應(yīng)該對(duì)比明顯,如常見的黑白 */ 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; /** * 生成二維碼 并 保存為圖片:write(RenderedImage im,String formatName,File output) * * @param codeContent :二維碼參數(shù)內(nèi)容,如果是一個(gè)網(wǎng)頁地址,如 https://www.baidu.com/ 則 微信掃一掃會(huì)直接進(jìn)入此地址 * 如果是一些參數(shù),如 1541656080837,則微信掃一掃會(huì)直接回顯這些參數(shù)值 * @param codeImgFileSaveDir :二維碼圖片保存的目錄,如 D:/codes * @param fileName :二維碼圖片文件名稱,帶格式,如 123.png */ public static void createCodeToFile(String codeContent, File codeImgFileSaveDir, String fileName) { try { /** 參數(shù)檢驗(yàn)*/ if (codeContent == null || "".equals(codeContent.trim())) { System.out.println("二維碼內(nèi)容為空,不進(jìn)行操作..."); return; } codeContent = codeContent.trim(); if (codeImgFileSaveDir == null || codeImgFileSaveDir.isFile()) { codeImgFileSaveDir = FileSystemView.getFileSystemView().getHomeDirectory(); System.out.println("二維碼圖片存在目錄為空,默認(rèn)放在桌面..."); } if (!codeImgFileSaveDir.exists()) { codeImgFileSaveDir.mkdirs(); System.out.println("二維碼圖片存在目錄不存在,開始創(chuàng)建..."); } if (fileName == null || "".equals(fileName)) { fileName = new Date().getTime() + ".png"; System.out.println("二維碼圖片文件名為空,隨機(jī)生成 png 格式圖片..."); } /**com.google.zxing.EncodeHintType:編碼提示類型,枚舉類型 * EncodeHintType.CHARACTER_SET:設(shè)置字符編碼類型 * 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:多格式寫入,這是一個(gè)工廠類,里面重載了兩個(gè) encode 方法,用于寫入條形碼或二維碼 * encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints) * contents:條形碼/二維碼內(nèi)容 * format:編碼類型,如 條形碼,二維碼 等 * width:碼的寬度 * height:碼的高度 * hints:碼內(nè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ù)的可訪問緩沖圖像,實(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); } } /**javax.imageio.ImageIO java 擴(kuò)展的圖像IO * write(RenderedImage im,String formatName,File output) * im:待寫入的圖像 * formatName:圖像寫入的格式 * output:寫入的圖像文件,文件不存在時(shí)會(huì)自動(dòng)創(chuàng)建 * * 即將保存的二維碼圖片文件*/ File codeImgFile = new File(codeImgFileSaveDir, fileName); ImageIO.write(bufferedImage, "png", codeImgFile); System.out.println("二維碼圖片生成成功:" + codeImgFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } /** * 生成二維碼 并 輸出到輸出流————通常用于輸出到網(wǎng)頁上進(jìn)行顯示 * 輸出到網(wǎng)頁與輸出到磁盤上的文件中,區(qū)別在于最后一句 ImageIO.write * write(RenderedImage im,String formatName,File output):寫到文件中 * write(RenderedImage im,String formatName,OutputStream output):輸出到輸出流中 * * @param codeContent :二維碼內(nèi)容 * @param outputStream :輸出流,比如 HttpServletResponse 的 getOutputStream */ public static void createCodeToOutputStream(String codeContent, OutputStream outputStream) { try { /** 參數(shù)檢驗(yàn)*/ if (codeContent == null || "".equals(codeContent.trim())) { System.out.println("二維碼內(nèi)容為空,不進(jìn)行操作..."); return; } codeContent = codeContent.trim(); /**com.google.zxing.EncodeHintType:編碼提示類型,枚舉類型 * EncodeHintType.CHARACTER_SET:設(shè)置字符編碼類型 * 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:多格式寫入,這是一個(gè)工廠類,里面重載了兩個(gè) encode 方法,用于寫入條形碼或二維碼 * encode(String contents,BarcodeFormat format,int width, int height,Map<EncodeHintType,?> hints) * contents:條形碼/二維碼內(nèi)容 * format:編碼類型,如 條形碼,二維碼 等 * width:碼的寬度 * height:碼的高度 * hints:碼內(nè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ù)的可訪問緩沖圖像,實(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); } } /** * 區(qū)別就是以一句,輸出到輸出流中,如果第三個(gè)參數(shù)是 File,則輸出到文件中 */ ImageIO.write(bufferedImage, "png", outputStream); System.out.println("二維碼圖片生成到輸出流成功..."); } catch (Exception e) { e.printStackTrace(); } } /** * 根據(jù)本地二維碼圖片————————解析二維碼內(nèi)容 * (注:圖片必須是二維碼圖片,但也可以是微信用戶二維碼名片,上面有名稱、頭像也是可以的) * * @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(); System.out.println("-----圖片非二維碼圖片:" + 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ò)誤,比如不能訪問,則 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(); System.out.println("-----二維碼圖片地址錯(cuò)誤:" + url); } catch (NotFoundException e) { e.printStackTrace(); System.out.println("-----圖片非二維碼圖片:" + url); } return resultStr; } public static void main(String[] args) throws MalformedURLException { File localFile = new File("E:\\logs\\1.png"); String localQRcodeContent = parseQRCodeByFile(localFile); System.out.println(localFile + " 二維碼內(nèi)容:" + localQRcodeContent); URL url = new URL("https://res.wx.qq.com/mpres/htmledition/images/mp_qrcode3a7b38.gif"); String netQRcodeContent = parseQRCodeByUrl(url); System.out.println(url + " 二維碼內(nèi)容:" + netQRcodeContent); } }
總結(jié)
到此這篇關(guān)于谷歌二維碼引擎com.google.zxing二維碼生成與解析的文章就介紹到這了,更多相關(guān)com.google.zxing二維碼生成解析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring SmartLifecycle:如何精準(zhǔn)控制Bean的生命周期
這篇文章主要介紹了Spring SmartLifecycle:如何精準(zhǔn)控制Bean的生命周期問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-03-03Presto支持Elasticsearch數(shù)據(jù)源配置詳解
這篇文章主要為大家介紹了Presto支持Elasticsearch數(shù)據(jù)源配置詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Java Springboot之Spring家族的技術(shù)體系
今天帶大家來學(xué)習(xí)Spring家族的技術(shù)體系,文中有非常詳細(xì)的圖文介紹及代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05Java Switch對(duì)各類型支持實(shí)現(xiàn)原理
這篇文章主要介紹了Java Switch對(duì)各類型支持實(shí)現(xiàn)原理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05Spring中的@ControllerAdvice三種用法詳解
這篇文章主要介紹了Spring中的@ControllerAdvice三種用法詳解,加了@ControllerAdvice的類為那些聲明了(@ExceptionHandler、@InitBinder或@ModelAttribute注解修飾的)方法的類而提供的<BR>專業(yè)化的@Component,以供多個(gè)Controller類所共享,需要的朋友可以參考下2024-01-01