java生成二維碼技術(shù)實(shí)現(xiàn)

一.maven依賴

下載google的二維碼工具包來(lái)進(jìn)行二維碼的生成九府,下面是jar包的maven下載

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

二.代碼部分

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
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 javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
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;

public class QRCodeUtils {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二維碼尺寸    
    private static final int QRCODE_SIZE = 300;
    // LOGO寬度    
    private static final int WIDTH = 60;
    // LOGO高度    
    private static final int HEIGHT = 60;

    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();
        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;
        }
        // 插入圖片    
        QRCodeUtils.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;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

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

    /**
     * 當(dāng)文件夾不存在時(shí)仑最,mkdirs會(huì)自動(dòng)創(chuàng)建多層目錄,區(qū)別于mkdir.(mkdir如果父目錄不存在則會(huì)拋出異常)  
     * @date 2013-12-11 上午10:16:36  
     * @param destPath 存放目錄  
     */
    public static void mkdirs(String destPath) {
        File file =new File(destPath);
        //當(dāng)文件夾不存在時(shí)宏浩,mkdirs會(huì)自動(dòng)創(chuàng)建多層目錄,區(qū)別于mkdir.(mkdir如果父目錄不存在則會(huì)拋出異常)    
        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 {
        QRCodeUtils.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 {
        QRCodeUtils.encode(content, null, destPath, needCompress);
    }

    /**
     * 生成二維碼  
     *
     * @param content
     *            內(nèi)容  
     * @param destPath
     *            存儲(chǔ)地址  
     * @throws Exception
     */
    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtils.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 = QRCodeUtils.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 {
        QRCodeUtils.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<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 QRCodeUtils.decode(new File(path));
    }

    public static void main(String[] args) throws Exception {
        String text = "http://www.baidu.com";  //這里設(shè)置自定義網(wǎng)站url
        String logoPath = "C:\\Users\\admin\\Desktop\\test\\test.jpg";
        String destPath = "C:\\Users\\admin\\Desktop\\test\\";
        System.out.println(QRCodeUtils.encode(text, logoPath, destPath, true));
    }
}  

三辱志、測(cè)試

image.png

打開(kāi)C:\Users\admin\Desktop\test目錄下的生成的二維碼圖片77286740.jpg,

掃碼就可以進(jìn)入設(shè)置的網(wǎng)址了狞膘。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末揩懒,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子挽封,更是在濱河造成了極大的恐慌已球,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辅愿,死亡現(xiàn)場(chǎng)離奇詭異智亮,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)点待,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門阔蛉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人癞埠,你說(shuō)我怎么就攤上這事状原。” “怎么了苗踪?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵遭笋,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我徒探,道長(zhǎng),這世上最難降的妖魔是什么喂窟? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任测暗,我火速辦了婚禮,結(jié)果婚禮上磨澡,老公的妹妹穿的比我還像新娘碗啄。我一直安慰自己,他們只是感情好稳摄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布稚字。 她就那樣靜靜地躺著,像睡著了一般厦酬。 火紅的嫁衣襯著肌膚如雪胆描。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,292評(píng)論 1 301
  • 那天仗阅,我揣著相機(jī)與錄音昌讲,去河邊找鬼。 笑死减噪,一個(gè)胖子當(dāng)著我的面吹牛短绸,可吹牛的內(nèi)容都是我干的车吹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼醋闭,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼窄驹!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起证逻,我...
    開(kāi)封第一講書(shū)人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤乐埠,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后瑟曲,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體饮戳,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年洞拨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扯罐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡烦衣,死狀恐怖歹河,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情花吟,我是刑警寧澤秸歧,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站衅澈,受9級(jí)特大地震影響键菱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜今布,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一经备、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧部默,春花似錦侵蒙、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至份蝴,卻和暖如春犁功,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背婚夫。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工波桩, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人请敦。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓镐躲,卻偏偏與公主長(zhǎng)得像储玫,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子萤皂,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

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