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

  • 本文非原創(chuàng),在哪找的忘了檀轨。
  • 使用Google的zxing蒙谓,當前最新的版本是3.3.3,可以訪問maven倉庫自行查看斥季。

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累驮、編寫幫助類

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      目標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();
    }

    /**
     * 生成二維碼(內嵌LOGO)
     *
     * @param content      內容
     * @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));
    }

    /**
     * 生成二維碼(內嵌LOGO)
     *
     * @param content      內容
     * @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));
    }


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

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

    /**
     * 生成二維碼
     *
     * @param content      內容
     * @param destPath     存儲地址
     * @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  內容
     * @param destPath 存儲地址
     * @throws Exception
     */
    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false);
    }

    /**
     * 生成二維碼(內嵌LOGO)
     *
     * @param content      內容
     * @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 內容
     * @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 不是二維碼的內容返回null, 是二維碼直接返回識別的結果
     * @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();
        }


        //驗證圖片是否含有二維碼
//        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 + "不是二維碼");
//        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末躁锡,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子置侍,更是在濱河造成了極大的恐慌映之,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蜡坊,死亡現場離奇詭異杠输,居然都是意外死亡,警方通過查閱死者的電腦和手機秕衙,發(fā)現死者居然都...
    沈念sama閱讀 92,987評論 3 395
  • 文/潘曉璐 我一進店門蠢甲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人据忘,你說我怎么就攤上這事峡钓。” “怎么了若河?”我有些...
    開封第一講書人閱讀 164,298評論 0 354
  • 文/不壞的土叔 我叫張陵能岩,是天一觀的道長。 經常有香客問我萧福,道長拉鹃,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,586評論 1 293
  • 正文 為了忘掉前任鲫忍,我火速辦了婚禮膏燕,結果婚禮上,老公的妹妹穿的比我還像新娘悟民。我一直安慰自己坝辫,他們只是感情好,可當我...
    茶點故事閱讀 67,633評論 6 392
  • 文/花漫 我一把揭開白布射亏。 她就那樣靜靜地躺著近忙,像睡著了一般竭业。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上及舍,一...
    開封第一講書人閱讀 51,488評論 1 302
  • 那天未辆,我揣著相機與錄音,去河邊找鬼锯玛。 笑死咐柜,一個胖子當著我的面吹牛,可吹牛的內容都是我干的攘残。 我是一名探鬼主播拙友,決...
    沈念sama閱讀 40,275評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼歼郭!你這毒婦竟也來了遗契?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,176評論 0 276
  • 序言:老撾萬榮一對情侶失蹤实撒,失蹤者是張志新(化名)和其女友劉穎姊途,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體知态,經...
    沈念sama閱讀 45,619評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡捷兰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,819評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了负敏。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贡茅。...
    茶點故事閱讀 39,932評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖其做,靈堂內的尸體忽然破棺而出顶考,到底是詐尸還是另有隱情,我是刑警寧澤妖泄,帶...
    沈念sama閱讀 35,655評論 5 346
  • 正文 年R本政府宣布驹沿,位于F島的核電站,受9級特大地震影響蹈胡,放射性物質發(fā)生泄漏渊季。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,265評論 3 329
  • 文/蒙蒙 一罚渐、第九天 我趴在偏房一處隱蔽的房頂上張望却汉。 院中可真熱鬧,春花似錦荷并、人聲如沸合砂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽翩伪。三九已至微猖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間幻工,已是汗流浹背励两。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評論 1 269
  • 我被黑心中介騙來泰國打工黎茎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留囊颅,地道東北人。 一個月前我還...
    沈念sama閱讀 48,095評論 3 370
  • 正文 我出身青樓傅瞻,卻偏偏與公主長得像踢代,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子嗅骄,可洞房花燭夜當晚...
    茶點故事閱讀 44,884評論 2 354