Google Zxing二维码生成与解析使用实例

应项目需求,现需要生成二维码功能,之前没怎么接触过这个知识点,上网狂搜,原来生成二维码的开源项目可谓是琳琅满目,SwetakeQRCode、BarCode4j、Qrcode、Zxing......

最后选择用Google Zxing,只所以选择Zxing,是因为Google龙头公司值得信赖。

废话不多说了,直接上代码

一、添加pom.xml依赖


    com.google.zxing
    core
    3.3.0


    com.google.zxing
    javase
    3.3.0

二、二维码工具类

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 hints = new HashMap();
            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 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");
    }
}

 

你可能感兴趣的:(java)