最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java生成與解析二維碼的完整指南

 更新時(shí)間:2026年05月17日 10:49:21   作者:RainCity  
二維碼是一種能夠?qū)⒋罅啃畔⒕幋a在小空間的編碼器,它是一種由黑白方塊構(gòu)成的圖片,可以將文本、鏈接、圖像等不同類型的信息編碼到其中,下面我們就來看看如何通過Java實(shí)現(xiàn)生成與解析二維碼吧

前言

二維碼是一種能夠?qū)⒋罅啃畔⒕幋a在小空間的編碼器。它是一種由黑白方塊構(gòu)成的圖片,可以將文本、鏈接、圖像等不同類型的信息編碼到其中。二維碼已經(jīng)廣泛應(yīng)用于不同的領(lǐng)域,如電子支付、電子門票、商品銷售等,這種快捷、高效的信息處理方式已成為現(xiàn)代生活中不可或缺的一部分。

所需依賴

<!-- 二維碼生成 -->
	<dependency>
	    <groupId>com.google.zxing</groupId>
	    <artifactId>core</artifactId>
	    <version>3.5.1</version>
	</dependency>
	<dependency>
	    <groupId>com.google.zxing</groupId>
	    <artifactId>javase</artifactId>
	    <version>3.5.1</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-mock</artifactId>
	    <version>2.0.8</version>
	    <scope>compile</scope>
	</dependency>

主要代碼

需要用到的一些常量

	/** 字符編碼 */
	private static final String CHARSET = "utf-8";

	/** 圖片格式 */
    private static final String FORMAT_NAME = "JPG";
    
    /** 二維碼尺寸 */
    private static final Integer QRCODE_SIZE = 380;
    
    /** LOGO寬度 */
    private static final Integer WIDTH = 100;
    
    /** LOGO高度 */
    private static final Integer HEIGHT = 100;

生成二維碼

	/**
     * 生成二維碼,得到 MultipartFile--通用
     * @param jsonString 二維碼內(nèi)容
     * @param logoPath logo路徑
     * @param bottomText 底部文字
     * @return {@link MultipartFile}
     * @ver v1.0.0
     */
    public static MultipartFile createQrCode(String jsonString, String logoPath, String bottomText) throws Exception {

        return initMultipartFile(jsonString, logoPath, bottomText);
    }

    /**
     * 生成二維碼,得到 MultipartFile-有l(wèi)ogo、無底部文字
     * @param jsonString 二維碼內(nèi)容
     * @param logoPath logo路徑
     * @return {@link MultipartFile}
     * @ver v1.0.0
     */
    public static MultipartFile createQrCode(String jsonString, String logoPath) throws Exception {

        return initMultipartFile(jsonString, logoPath, null);
    }

    /**
     * 生成二維碼,得到 MultipartFile-無logo、無底部文字
     * @param jsonString 二維碼內(nèi)容
     * @return {@link MultipartFile}
     * @ver v1.0.0
     */
    public static MultipartFile createQrCode(String jsonString) throws Exception {

        return initMultipartFile(jsonString, null, null);
    }

    /**
     * 生成二維碼
     * @param content 二維碼內(nèi)容
     * @param logoPath logo路徑
     * @param bottomText 底部文字
     * @return {@link MultipartFile}
     * @ver v1.0.0
     */
    private static MultipartFile initMultipartFile(String content, String logoPath, String bottomText) throws Exception {
        //二維碼名稱
        String qrName = "qr" + System.currentTimeMillis() + ".jpg";

        int height = 0;
        if (StringUtils.hasText(bottomText)) {
            height = 10;
        }

        //得到BufferedImage對(duì)象
        BufferedImage bufferedImage = createImage(content, logoPath, true, height);
        // 判斷是否添加底部文字
        if (StringUtils.hasText(bottomText)) {
            addBottomText(bufferedImage, bottomText);
        }

        //創(chuàng)建一個(gè)ByteArrayOutputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //把BufferedImage寫入ByteArrayOutputStream
        ImageIO.write(bufferedImage, "jpg", os);
        //ByteArrayOutputStream轉(zhuǎn)成InputStream
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        //InputStream轉(zhuǎn)成MultipartFile
        return new MockMultipartFile("qrFile", qrName, "text/plain", input);
    }

    /**
     * 生成 BufferedImage
     * @param content 存放在二維碼中的內(nèi)容
     * @param imgPath logo的路徑及名稱
     * @param needCompress 是否需要壓縮
     * @param height 額外高度(有底部文字時(shí))
     * @return {@link BufferedImage}
     * @ver v1.0.0
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress, int height) 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 bitWidth = bitMatrix.getWidth();
        int bitHeight = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(bitWidth, bitHeight + height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitWidth; x++) {
            for (int y = 0; y < bitHeight; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入logo圖片
        insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 插入logo圖片
     * @param source 二維碼
     * @param logoPath logo的路徑及名稱
     * @param needCompress 是否需要壓縮
     * @ver v1.0.0
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            log.error(logoPath + "   該文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(logoPath));
        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 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();
    }

    /**
     * 二維碼底部添加文字
     * @param source 二維碼
     * @param bottomText 底部文字
     * @ver v1.0.0
     */
    private static void addBottomText(BufferedImage source, String bottomText) {
        //生成image
        int defineWidth = QRCODE_SIZE;
        int defineHeight = 20;
        BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, 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, defineWidth, defineHeight);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        //部署linux需要注意 linux無此字體會(huì)顯示方塊
        Font font = new Font("微軟雅黑", Font.BOLD, 15);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(bottomText, context);

        FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
        Rectangle rec = font.getStringBounds(bottomText, frc).getBounds();
        double fontWidth = rec.getWidth();
        double offset = (defineWidth - fontWidth) / 2;

        float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        g2.drawString(bottomText, (int) offset, (int) y);

        Graphics2D graph = source.createGraphics();
        //開啟文字抗鋸齒
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //添加image
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        graph.drawImage(textImage, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);
        graph.dispose();
    }

二維碼解析

	/**
     * 根據(jù)二維碼路徑解析二維碼
     * @param path 二維碼路徑
     * @return {@link String}
     * @ver v1.0.0
     */
    public static String decode(String path) throws Exception {
        return decode(new File(path));
    }
    
    /**
     * 根據(jù)二維碼文件解析二維碼
     * @param file 二維碼文件
     * @return {@link String}
     * @ver v1.0.0
     */
    public static String decode(File file) throws Exception {
        BufferedImage 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);
        return result.getText();
    }

是不是很簡(jiǎn)單0.0 好了,到這就結(jié)束啦!??!

以上就是Java生成與解析二維碼的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Java生成與解析二維碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • idea配置SVN的教程

    idea配置SVN的教程

    文章介紹了如何安裝和配置TortoiseSVN以及在IntelliJ?IDEA中配置SVN,首先,安裝TortoiseSVN時(shí)需要選擇與電腦配置相匹配的版本,并確保安裝命令行客戶端工具,其次,在IntelliJ?IDEA中配置SVN時(shí),需要指定SVN可執(zhí)行文件的路徑
    2025-01-01
  • Java泛型類型擦除

    Java泛型類型擦除

    這篇文章主要為大家詳細(xì)介紹了Java泛型類型擦除,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Java實(shí)現(xiàn)MD5加密算法方法例子

    Java實(shí)現(xiàn)MD5加密算法方法例子

    這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)MD5加密算法方法的相關(guān)資料,MD5加密是一種常見的加密方式,我們經(jīng)常用在保存用戶密碼和關(guān)鍵信息上,需要的朋友可以參考下
    2023-10-10
  • Java classloader類加載器的實(shí)現(xiàn)

    Java classloader類加載器的實(shí)現(xiàn)

    本文介紹了Java類加載器的繼承性和隔離性,類加載器分為四個(gè)層級(jí):Bootstrap、Extension、System和Plugin,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2025-12-12
  • 詳解java操作Redis數(shù)據(jù)庫(kù)的redis工具(RedisUtil,jedis工具JedisUtil,JedisPoolUtil)

    詳解java操作Redis數(shù)據(jù)庫(kù)的redis工具(RedisUtil,jedis工具JedisUtil,JedisPoo

    這篇文章主要介紹了java操作Redis數(shù)據(jù)庫(kù)的redis工具,包括RedisUtil,jedis工具JedisUtil,JedisPoolUtil工具,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2021-08-08
  • jar中VO的探究

    jar中VO的探究

    這篇文章主要介紹了jar中VO的探究的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • Java基礎(chǔ)之java處理ip的工具類

    Java基礎(chǔ)之java處理ip的工具類

    這篇文章主要介紹了Java基礎(chǔ)應(yīng)用,使用java處理ip的工具類的相關(guān)資料,需要的朋友可以參考下
    2014-10-10
  • 簡(jiǎn)單了解springboot eureka交流機(jī)制

    簡(jiǎn)單了解springboot eureka交流機(jī)制

    這篇文章主要介紹了簡(jiǎn)單了解springboot eureka交流機(jī)制,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • ???????Spring多租戶數(shù)據(jù)源管理 AbstractRoutingDataSource

    ???????Spring多租戶數(shù)據(jù)源管理 AbstractRoutingDataSource

    本文技術(shù)了???????Spring多租戶數(shù)據(jù)源管理 AbstractRoutingDataSource,下文詳細(xì)內(nèi)容介紹,需要的小伙伴可以參考一下
    2022-05-05
  • Spring Boot 類加載流程分析

    Spring Boot 類加載流程分析

    本文給大家介紹Spring Boot 類加載流程分析,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2026-03-03

最新評(píng)論

留坝县| 新野县| 中方县| 广饶县| 镶黄旗| 高唐县| 伊春市| 东平县| 疏勒县| 视频| 健康| 历史| 察隅县| 宜州市| 肃南| 屏东市| 嘉义市| 鹰潭市| 安阳市| 常宁市| 郸城县| 密山市| 玉屏| 崇州市| 进贤县| 平罗县| 玉屏| 乌恰县| 滕州市| 东乡县| 吉安市| 天镇县| 郸城县| 清原| 合肥市| 白沙| 霍邱县| 社旗县| 庆阳市| 绥滨县| 开封县|