1. 程式人生 > >Java 中使用 google.zxing 快捷生成二維碼(附工具類原始碼)

Java 中使用 google.zxing 快捷生成二維碼(附工具類原始碼)

移動網際網路時代,基於手機端的各種活動掃碼和收付款碼層出不窮;那我們如何在Java中生成自己想要的二維碼呢?下面就來講講在Java開發中使用 google.zxing 生成二維碼。


一般情況下,Java生成二維碼的方式有三種,一種是基於 google.zxing ,是google公司出的;一種是基於 jp.sourceforge.qrcode ,日本一家公司開發的;還有一種是基於 jquery.qrcode.jsjquery 外掛。比較常用的是 google.zxing 的方式,這裡我們就以其為例子講解如何生成二維碼。

1、使用Maven版本控制

這裡使用 Maven

來控制版本,如果想要檢視最新使用的版本,可以去 http://maven.aliyun.com/nexus/#nexus-search;quick~zxing 上面檢視,示例使用的版本是3.3.0,引用如下:

<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.3.0</version>
</dependency>
複製程式碼

2、生成/解碼二維碼工具類

下面已經封裝好了一個生成二維碼的工具類以供參考:

package com.yclimb.zxing;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 二維碼生成工具類
 *
 * @author yclimb
 * @date 2018/4/23
 */
public class QRCodeUtil {

    private static Logger log
= LoggerFactory.getLogger(QRCodeUtil.class); /** * 生成二維碼 * @param text 內容,可以是連結或者文字 * @param path 生成的二維碼位置 */ public static void encodeQRCode(String text, String path) { encodeQRCode(text, path, null, null, null); } /** * 生成二維碼 * @param text 內容,可以是連結或者文字 * @param path 生成的二維碼位置 * @param width 寬度,預設300 * @param height 高度,預設300 * @param format 生成的二維碼格式,預設png */ public static void encodeQRCode(String text, String path, Integer width, Integer height, String format) { try { // 得到檔案物件 File file = new File(path); // 判斷目標檔案所在的目錄是否存在 if(!file.getParentFile().exists()) { // 如果目標檔案所在的目錄不存在,則建立父目錄 log.info("目標檔案所在目錄不存在,準備建立它!"); if(!file.getParentFile().mkdirs()) { log.info("建立目標檔案所在目錄失敗!"); return; } } // 寬 if (width == null) { width = 300; } // 高 if (height == null) { height = 300; } // 圖片格式 if (format == null) { format = "png"; } // 設定字符集編碼 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 生成二維碼矩陣 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); // 二維碼路徑 Path outputPath = Paths.get(path); // 寫入檔案 MatrixToImageWriter.writeToPath(bitMatrix, format, outputPath); } catch (Exception e) { log.error(e.getMessage(), e); } } /** * 對二維碼圖片進行解碼 * @param filePath 二維碼路徑 * @return 解碼後對內容 */ public static JSONObject decodeQRCode(String filePath) { try { // 讀取圖片 BufferedImage image = ImageIO.read(new File(filePath)); // 多步解析 LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); // 一步到位 // BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))) // 設定字符集編碼 Map<DecodeHintType, String> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 對影象進行解碼 Result result = new MultiFormatReader().decode(binaryBitmap, hints); // 解碼內容 JSONObject content = JSONObject.parseObject(result.getText()); System.out.println("圖片內容: "); System.out.println("content: " + content.toJSONString()); System.out.println("圖片中格式: "); System.out.println("encode: " + result.getBarcodeFormat()); return content; } catch (Exception e) { log.error(e.getMessage(), e); } return null; } } 複製程式碼

3、測試方法

public static void main(String[] args) {

   // 生成路徑
   String filePath = "/Users/yclimb/Documents/tmp/first.png";

   // 生成二維碼
   encodeQRCode("第一個二維碼", filePath);

   // 解碼二維碼
   decodeQRCode(filePath);
}
複製程式碼

結語

到此本文就結束了,關注公眾號檢視更多推送!!!


關注我的公眾號