Java 二維碼生成與解析(com.google.zxing)

  • 本文非原創(chuàng),在哪找的忘了。
  • 使用Google的zxing,當(dāng)前最新的版本是3.3.3,可以訪問(wèn)maven倉(cāng)庫(kù)自行查看。

1、添加maven依賴

       <!-- google qrc -->
       <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>

2、編寫(xiě)幫助類

package com.demo.jpa.util;

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 java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

/**
 * 二維碼工具類
 * Created by fuli.shen on 2017/3/31.
 */
public class QRCodeUtil {

    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二維碼尺寸
    private static final int QRCODE_SIZE = 3189;
    // LOGO寬度
    private static final int WIDTH = 640;
    // LOGO高度
    private static final int HEIGHT = 640;

    /**
     * 生成二維碼的方法
     *
     * @param content      目標(biāo)URL
     * @param imgPath      LOGO圖片地址
     * @param needCompress 是否壓縮LOGO
     * @return 二維碼圖片
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入圖片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source       二維碼圖片
     * @param imgPath      LOGO圖片地址
     * @param needCompress 是否壓縮
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   該文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 壓縮LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 繪制縮小后的圖
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        // logo背景
        int tmp = 120;
        int arc = 120;
        graph.setColor(Color.WHITE);
        graph.fillRoundRect(x - tmp, y - tmp, width + tmp * 2, width + tmp * 2, arc, arc);
        // logo邊框
        Shape shape = new RoundRectangle2D.Float(x - tmp, y - tmp, width + tmp * 2, width + tmp * 2, arc, arc);
        graph.setStroke(new BasicStroke(6f));
        graph.setColor(new Color(0, 166, 254));
        graph.draw(shape);

        // logo
        graph.drawImage(src, x, y, width, height, null);

        graph.dispose();
    }

    /**
     * 生成二維碼(內(nèi)嵌LOGO)
     *
     * @param content      內(nèi)容
     * @param imgPath      LOGO地址
     * @param destPath     存放目錄
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        String file = new Random().nextInt(99999999) + ".jpg";
        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
    }

    /**
     * 生成二維碼(內(nèi)嵌LOGO)
     *
     * @param content      內(nèi)容
     * @param imgPath      LOGO地址
     * @param destPath     存放目錄
     * @param destName     保存名稱(帶后綴)
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, String destName, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + destName));
    }


    /**
     * 當(dāng)文件夾不存在時(shí),mkdirs會(huì)自動(dòng)創(chuàng)建多層目錄,區(qū)別于mkdir.(mkdir如果父目錄不存在則會(huì)拋出異常)
     *
     * @param destPath 存放目錄
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 生成二維碼(內(nèi)嵌LOGO)
     *
     * @param content  內(nèi)容
     * @param imgPath  LOGO地址
     * @param destPath 存儲(chǔ)地址
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath) throws Exception {
        QRCodeUtil.encode(content, imgPath, destPath, false);
    }

    /**
     * 生成二維碼
     *
     * @param content      內(nèi)容
     * @param destPath     存儲(chǔ)地址
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String destPath, boolean needCompress) throws Exception {
        QRCodeUtil.encode(content, null, destPath, needCompress);
    }

    /**
     * 生成二維碼
     *
     * @param content  內(nèi)容
     * @param destPath 存儲(chǔ)地址
     * @throws Exception
     */
    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false);
    }

    /**
     * 生成二維碼(內(nèi)嵌LOGO)
     *
     * @param content      內(nèi)容
     * @param imgPath      LOGO地址
     * @param output       輸出流
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,
                needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    /**
     * 生成二維碼
     *
     * @param content 內(nèi)容
     * @param output  輸出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }

    /**
     * 解析二維碼
     *
     * @param file 二維碼圖片
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }

        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二維碼
     *
     * @param path 二維碼圖片地址
     * @return 不是二維碼的內(nèi)容返回null, 是二維碼直接返回識(shí)別的結(jié)果
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

    public static void main(String[] args) {

        // 生成二維碼
        String text = "www.baidu.com";
//        String imagePath = System.getProperty("user.dir") + "\\logo.png";
        String imagePath = "com/demo/jpa/util/logo.png";
//        E:\DEVELOPE\Code\Demo\genqrc\src\main\java\com\demo\genqrc\logo.png
        String destPath = System.getProperty("user.dir");
        try {
            QRCodeUtil.encode(text, imagePath, destPath, true);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //驗(yàn)證圖片是否含有二維碼
//        String destPath1 = System.getProperty("user.dir") + "/data/3.jpg";

//        try {
//            String result = decode(dp);
//            System.out.println(result);
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println(dp + "不是二維碼");
//        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容