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

移動互聯網時代,基於手機端的各類活動掃碼和收付款碼層出不窮;那咱們如何在Java中生成本身想要的二維碼呢?下面就來說講在Java開發中使用 google.zxing 生成二維碼。java


通常狀況下,Java生成二維碼的方式有三種,一種是基於 google.zxing ,是google公司出的;一種是基於 jp.sourceforge.qrcode ,日本一家公司開發的;還有一種是基於 jquery.qrcode.jsjquery 插件。比較經常使用的是 google.zxing 的方式,這裏咱們就以其爲例子講解如何生成二維碼。jquery

一、使用Maven版本控制

這裏使用 Maven 來控制版本,若是想要查看最新使用的版本,能夠去 http://maven.aliyun.com/nexus/#nexus-search;quick~zxing 上面查看,示例使用的版本是3.3.0,引用以下:json

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

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

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

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;
    }
}

複製代碼

三、測試方法

public static void main(String[] args) {

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

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

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

結語

到此本文就結束了,關注公衆號查看更多推送!!!maven


關注個人公衆號
相關文章
相關標籤/搜索