二維碼的工具類


新建一個(gè)工具類:QRCodeUtil
引入兩個(gè)主要的依賴:

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


基本的一些屬性:

    private static final Logger logger = Logger.getLogger(QRCodeUtil.class.getName());
    private static final String CHARSET = "UTF-8";
    private static final String FORMAT_NAME = "JPG";

    private static final int QRCODE_SIZE = 300;
    private static final int WIDTH = 60;
    private static final int HEIGHT = 60;

創(chuàng)建createImage

package com.example.demotest;

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;
import java.util.logging.Logger;

/**
 * @Author 劉德意 -HP
 * @Date 2021/9/17  9:35
 * @Description: 二維碼的工具類
 */
public class QRCodeUtil {
    private static final Logger logger = Logger.getLogger(QRCodeUtil.class.getName());
    private static final String CHARSET = "UTF-8";
    private static final String FORMAT_NAME = "JPG";

    private static final int QRCODE_SIZE = 300;
    private static final int WIDTH = 60;
    private static final int HEIGHT = 60;
    //QRCodeWriter;
    //QRCodeReader

    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        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();

        //Image是一個(gè)抽象列,BufferedImage是Image的實(shí)現(xiàn)。Image和BufferedImage的主要作用就是將一副圖片加載到內(nèi)存中。
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                image.setRGB(i, j, bitMatrix.get(i, j) ? 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()){
            logger.warning(imgPath +":該文件不存在!");
            return;
        }

        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);

        //壓縮logo
        if (needCompress){
            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 graphics = tag.getGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();
        }

        //插入LOGO
        Graphics2D graphics2D = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graphics2D.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
        graphics2D.setStroke(new BasicStroke(3f));
        graphics2D.draw(shape);
        graphics2D.dispose();

    }

    /**
     * 生成二維碼,內(nèi)嵌LGOG
     * @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(9999) + ".jpg";
        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
    }

    /**
     * 當(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.mkdirs();
        }
    }

    /**
     *
     * @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);
    }

    /**
     * 生產(chǎn)二維碼
     * @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 imgPahth LOGO地址
     * @param outputStream 輸出流
     * @param needCompress 是否壓縮LOGO
     * @throws Exception
     */
    public static void encode(String content, String imgPahth, OutputStream outputStream, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPahth, needCompress);
        ImageIO.write(image, FORMAT_NAME, outputStream);
    }

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

    /**
     * 解析二維碼
     * @param file 二維碼文件
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (null == image){
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二維碼
     * @param path 二維碼圖片地址
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

    /**
     *
     * @param text
     * @param picturePath
     * @param location
     * @throws Exception
     */
    public static void createCode(String text, String picturePath, String location) throws Exception {
        QRCodeUtil.encode(text, picturePath, location, true);
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末奏篙,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子迫淹,更是在濱河造成了極大的恐慌秘通,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件敛熬,死亡現(xiàn)場(chǎng)離奇詭異肺稀,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)应民,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門话原,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人诲锹,你說(shuō)我怎么就攤上這事繁仁。” “怎么了归园?”我有些...
    開(kāi)封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵黄虱,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我庸诱,道長(zhǎng)捻浦,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任桥爽,我火速辦了婚禮默勾,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘聚谁。我一直安慰自己母剥,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布形导。 她就那樣靜靜地躺著环疼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪朵耕。 梳的紋絲不亂的頭發(fā)上炫隶,一...
    開(kāi)封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天,我揣著相機(jī)與錄音阎曹,去河邊找鬼伪阶。 笑死煞檩,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的栅贴。 我是一名探鬼主播斟湃,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼檐薯!你這毒婦竟也來(lái)了凝赛?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤坛缕,失蹤者是張志新(化名)和其女友劉穎墓猎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體赚楚,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡毙沾,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了宠页。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片左胞。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖勇皇,靈堂內(nèi)的尸體忽然破棺而出罩句,到底是詐尸還是另有隱情焚刺,我是刑警寧澤敛摘,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站乳愉,受9級(jí)特大地震影響兄淫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜蔓姚,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一捕虽、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧坡脐,春花似錦泄私、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至恬砂,卻和暖如春咧纠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背泻骤。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工漆羔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留梧奢,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓演痒,卻偏偏與公主長(zhǎng)得像亲轨,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子嫡霞,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容