Google Zxing二維碼生成與解析使用實例

應項目需求,現需要生成二維碼功能,之前沒怎麼接觸過這個知識點,上網狂搜,原來生成二維碼的開源項目可謂是琳琅滿目,SwetakeQRCode、BarCode4j、Qrcode、Zxing......

最後選擇用Google Zxing,只所以選擇Zxing,是因爲Google龍頭公司值得信賴。

廢話不多說了,直接上代碼

一、添加pom.xml依賴

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.0</version>
</dependency>

二、二維碼工具類

package com.fintech.common.utils;

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.io.FileInputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * 二維碼工具類
 */
public class ZxingUtil {

    private static Logger logger = LoggerFactory.getLogger(ZxingUtil.class);

    /**
     * 生成二維碼
     * @param text  內容
     * @param dir   圖像路徑
     * @throws Exception
     */
    public static String createQrcode(String text, String dir) throws Exception {
        String result = "";
        logger.info("生成二維碼開始,內容:{},路徑:{}",text, dir );
        String content = text;  // 內容
        int width = 300;    // 圖像寬度
        int height = 300;   // 圖像高度
        String format = "png";  // 圖像類型
        try{
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);  // 生成矩陣
            File file = new File(dir);
            if(!file.exists()){
                file.mkdir();
            }
            Path path = FileSystems.getDefault().getPath(dir + "//" + System.currentTimeMillis() + "." + format);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);   // 輸出圖像
            result = path.toString();
            logger.info("生成二維碼成功,路徑:{}", result);
        }catch (Exception e){
            throw new Exception("生成二維碼異常!");
        }
        return result;
    }

    /**
     * 解析二維碼
     * @param path 路徑
     * @return
     * @throws Exception
     */
    public static String decodeQrcode(String path) throws Exception {
        logger.info("解析二維碼開始,路徑:{}", path);
        String retStr = "";
        if ("".equalsIgnoreCase(path) && path.length() == 0) {
            return "解析二維碼路徑爲空!";
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(path));
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap bitmap = new BinaryBitmap(binarizer);
            HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
            hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
            retStr = result.getText();
            logger.info("解析二維碼成功,內容:{}", retStr);
        } catch (Exception e) {
            throw new Exception("解析二維碼異常!");
        }
        return retStr;
    }

    public static void main(String[] args) throws Exception {
        createQrcode("https://blog.csdn.net/u010688241/article/details/82866135","D://qrcode");
        decodeQrcode("D:\\qrcode\\1548740566253.png");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章