根據(jù)鏈接生成二維碼

內(nèi)容轉(zhuǎn)載于網(wǎng)絡搓萧,原文鏈接:https://blog.csdn.net/m0_47104939/article/details/125639363
pom文件引入

<!--Java 生成二維碼 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>


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 sun.font.FontDesignMetrics;
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
 
public class QRCodeUtil {
    /**
     * 創(chuàng)建二維碼
     * @param charSet 編碼方式
     * @param content 二維碼內(nèi)容
     * @param qrWidth 二維碼長度
     * @param qrHeight 二維碼高度
     * @return
     */
    public static BufferedImage createImage(String charSet, String content, int qrWidth, int qrHeight){
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, charSet);
        hints.put( EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,qrWidth , qrHeight, // 修改二維碼底部高度
                    hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        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);
            }
        }
        return image;
    }
 
    /**
     * 對已經(jīng)生成好的二維碼設置logo
     * @param source 二維碼
     * @param logo logo圖片
     * @param logoWidth logo寬度
     * @param logoHeight logo高度
     */
    public static void insertLogoImage(BufferedImage source,Image logo,int logoWidth,int logoHeight){
        Graphics2D graph = source.createGraphics();
        int qrWidth = source.getWidth();
        int qrHeight = source.getHeight();
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;
        graph.drawImage(logo, x, y, logoWidth, logoHeight, null);
        Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }
 
    /**
     * 縮小logo圖片
     * @param logoPath
     * @param logoWidth
     * @param logoHeight
     * @return
     */
    public static Image compressLogo(String logoPath, int logoWidth, int logoHeight){
        File file = new File(logoPath);
        if (!file.exists()) {
            System.err.println("" + logoPath + "   該文件不存在!");
            return null;
        }
        Image original = null;
        try {
            original = ImageIO.read(new File(logoPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        int width = original.getWidth(null);
        int height = original.getHeight(null);
        if (width > logoWidth) {
            width = logoWidth;
        }
        if (height > logoHeight) {
            height = logoHeight;
        }
        Image image = original.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();
        return image;
    }
 
    /**
     * 增加底部的說明文字
     * @param source 二維碼
     * @param text 說明內(nèi)容
     * @param step
     */
    public static BufferedImage addBottomFont(BufferedImage source, String text,int step) {
 
        int qrWidth = source.getWidth();
        System.out.println("二維碼的寬度"+qrWidth);
        int qrHeight = source.getHeight();
        System.out.println("二維碼的高度"+qrHeight);
        BufferedImage textImage = textToImage(text, qrWidth, 20,16);
        Graphics2D graph = source.createGraphics();
        //開啟文字抗鋸齒
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
 
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);
 
        Image src = textImage;
        graph.drawImage(src, 0, qrHeight - (20 * step) - 10, width, height, null);
        graph.dispose();
        return  source;
    }
 
    /**
     * 將文明說明增加到二維碼上
     * @param str       文字
     * @param width     寬
     * @param height    高
     * @param fontSize 字體大小
     * @return
     */
    public static BufferedImage textToImage(String str, int width, int height,int fontSize) {
        BufferedImage textImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)textImage.getGraphics();
        //開啟文字抗鋸齒
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("微軟雅黑", Font.PLAIN, fontSize);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(str, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (width - fontMetrics.stringWidth(str)) / 2;
        float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        g2.drawString(str, (int)offset, (int)y);
        return textImage;
    }
 
    /**
     * 頂部增加說明文字
     * @param source
     * @param text
     */
    public static void addUpFont(BufferedImage source, String text) {
        int qrWidth = source.getWidth();
        int qrHeight = source.getHeight();
 
        BufferedImage textImage = textToImage(text, qrWidth, 10,10);
        Graphics2D graph = source.createGraphics();
        //開啟文字抗鋸齒
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
 
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);
 
        Image src = textImage;
        graph.drawImage(src, 0, 4, width, height, null);
        graph.dispose();
    }
 
    /**
     * 生成二維碼圖片
     * @param charSet 二維碼編碼方式
     * @param content 內(nèi)容
     * @param qrWidth 寬度
     * @param qrHeight 長度
     * @param formatName jpg等圖片格式
     * @param imgPath 二維碼存放路徑
     */
    public static void encode(String charSet,String content,int qrWidth,int qrHeight,String formatName,String imgPath){
        BufferedImage image = QRCodeUtil.createImage(charSet,content,qrWidth,qrHeight);
        try {
            ImageIO.write(image, formatName, new File(imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 生成二維碼圖片流
     * @param charSet 二維碼編碼方式
     * @param content 內(nèi)容
     * @param qrWidth 寬度
     * @param qrHeight 長度
     * @return
     */
    public static BufferedImage encode(String charSet,String content,int qrWidth,int qrHeight) {
        BufferedImage image = QRCodeUtil.createImage(charSet,content,qrWidth,qrHeight);
        return image;
    }
 
    public static void encode( BufferedImage image,String formatName,String imgPath){
        try {
 
            ImageIO.write(image, formatName, new File(imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 當文件夾不存在時宛畦,mkdirs會自動創(chuàng)建多層目錄瘸洛,區(qū)別于mkdir.(mkdir如果父目錄不存在則會拋出異常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }
 
    /*
     * 解析二維碼
     */
    public static String decode(File file, String cherSet) 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, cherSet);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

public static void main(String[] args) {
        String url = "https://www.baidu.com";
        BufferedImage image = QRCodeUtil.createImage("utf-8", url, 300, 300);
        QRCodeUtil.addUpFont(image, "baidu");
        String imagePath = null;
        String path = null;
        File file = new File("本地要存儲的路徑");
        try {
            ImageIO.write(image, "JPEG", file);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
        System.out.println("生成二維碼成功!");
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末次和,一起剝皮案震驚了整個濱河市反肋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌踏施,老刑警劉巖石蔗,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罕邀,死亡現(xiàn)場離奇詭異,居然都是意外死亡养距,警方通過查閱死者的電腦和手機燃少,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來铃在,“玉大人,你說我怎么就攤上這事碍遍《ㄍ” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵怕敬,是天一觀的道長揣炕。 經(jīng)常有香客問我,道長东跪,這世上最難降的妖魔是什么畸陡? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮虽填,結(jié)果婚禮上丁恭,老公的妹妹穿的比我還像新娘。我一直安慰自己斋日,他們只是感情好牲览,可當我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著恶守,像睡著了一般第献。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上兔港,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天庸毫,我揣著相機與錄音,去河邊找鬼衫樊。 笑死飒赃,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的科侈。 我是一名探鬼主播盒揉,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼兑徘!你這毒婦竟也來了刚盈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤挂脑,失蹤者是張志新(化名)和其女友劉穎藕漱,沒想到半個月后欲侮,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡肋联,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年威蕉,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片橄仍。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡韧涨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出侮繁,到底是詐尸還是另有隱情虑粥,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布宪哩,位于F島的核電站娩贷,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏锁孟。R本人自食惡果不足惜彬祖,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望品抽。 院中可真熱鬧储笑,春花似錦、人聲如沸圆恤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽哑了。三九已至赘方,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間弱左,已是汗流浹背窄陡。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留拆火,地道東北人跳夭。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像们镜,于是被迫代替她去往敵國和親币叹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,435評論 2 359

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