SpringBoot生成和解析二维码完整工具类分享(提供Gitee源码)

news/2024/5/17 17:48:43 标签: spring boot, gitee, 后端, 二维码, java, junit, spring

前言:在日常的开发工作当中可能需要实现一个二维码小功能,我参考了网上很多关于SpringBoot生成二维码的教程,最终还是自己封装了一套完整生成二维码的工具类,可以支持基础的黑白二维码、带颜色的二维码、带Logo的二维码、带颜色和Logo的二维码和解析二维码五大功能,还可以生成具体的二维码文件或返回Base64,都是博主自己手写封装好的,这边免费开源给大家一键使用!只求大家一个免费的三连支持!

目录

一、问题记录

二、导入pom依赖

三、QRCodeUtil工具类完整代码

四、使用示例

五、Gitee源码

六、总结


一、问题记录

这边我使用的是zxing提供的jar包生成的二维码,不过有1个问题博客目前暂时未解决,如果有解决的方法希望可以在评论区交流一下,问题如下:

二维码的内容如果设置为中文,会报com.google.zxing.NotFoundException的错误,这个问题博主搜索了网上很多的信息也没有找到具体的解决方案。

二、导入pom依赖

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 二维码生成器依赖 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

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

        <!-- 常用工具类 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>

三、QRCodeUtil工具类完整代码

java">package com.example.ewm.utils;

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.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author HTT
 */
@Component
public class QRCodeUtil {
    /**
     * 编码格式
     */
    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;

    /**
     * 插入图片
     * @param source 文件流
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @throws Exception
     */
    private void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            throw new Exception(imgPath+"图片文件不存在");
        }
        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 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 content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @return
     * @throws Exception
     */
    private BufferedImage createEwm(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable(16);
        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 (StringUtils.isEmpty(imgPath)) {
            return image;
        }
        // 插入图片
        insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 创建自定义颜色和图片的二维码核心方法(如果图片路径为空,不会生成图片)
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @param frontColor 前景色
     * @param backgroundColor 背景色
     * @return
     * @throws Exception
     */
    private BufferedImage createEwm(String content, String imgPath, boolean needCompress,int frontColor,int backgroundColor) throws Exception {
        Hashtable hints = new Hashtable(16);
        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) ? frontColor : backgroundColor);
            }
        }
        if (StringUtils.isEmpty(imgPath)) {
            return image;
        }
        // 插入图片
        insertImage(image, imgPath, needCompress);
        return image;
    }

    /**
     * 生成带图片的二维码保存为文件(如果图片路径为空,不会生成图片)
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param destPath 存放路径
     * @param needCompress 是否压缩图片
     * @throws Exception
     */
    private void generate(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = createEwm(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    /**
     * 创建自定义颜色和图片的二维码保存为文件(如果图片路径为空,不会生成图片)
     * @param content 二维码内容
     * @param imgPath 图片路径(路径为空,则只生成基础的二维码)
     * @param destPath 存放路径
     * @param needCompress 是否压缩图片
     * @param frontColor 前景色
     * @param backgroundColor 背景色
     * 例举一些16进制的颜色代码
     * 0x000000 黑
     * 0xff0000 亮红
     * 0x00ff00 亮绿
     * 0xffff00 亮黄
     * 0x0000ff 亮蓝
     * 0xff00ff 亮紫
     * 0x00ffff 亮浅蓝
     * 0xffffff 白
     * 0xc6c6c6 亮灰
     * 0x848484 暗灰
     * @throws Exception
     */
    private void generate(String content, String imgPath, String destPath, boolean needCompress,int frontColor,int backgroundColor) throws Exception {
        BufferedImage image = createEwm(content, imgPath, needCompress,frontColor,backgroundColor);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    /**
     * 生成带有图片的二维码并返回Base64(如果图片路径为空,不会生成图片)
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @return
     * @throws Exception
     */
    private String generateBase64(String content, String imgPath, boolean needCompress) throws Exception {
        if (!StringUtils.isEmpty(content)) {
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 0);
            BufferedImage bufferedImage = createEwm(content, imgPath, needCompress);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, FORMAT_NAME, os);
            String base64 = Base64.encode(os.toByteArray());
            os.flush();
            os.close();
            return "data:image/png;base64," + base64;
        }
        return "";
    }

    /**
     * 生成带有自定义颜色和图片的二维码并返回Base64(如果图片路径为空,不会生成图片)
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @param frontColor 前景色
     * @param backgroundColor 背景色
     * @return
     * @throws Exception
     */
    private String generateBase64(String content, String imgPath, boolean needCompress,int frontColor,int backgroundColor) throws Exception {
        if (!StringUtils.isEmpty(content)) {
            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 0);
            BufferedImage bufferedImage = createEwm(content, imgPath, needCompress,frontColor,backgroundColor);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, FORMAT_NAME, os);
            String base64 = Base64.encode(os.toByteArray());
            os.flush();
            os.close();
            return "data:image/png;base64," + base64;
        }
        return "";
    }

    /**
     * 创建多级目录
     * @param destPath
     */
    private void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 根据文件解析二维码
     * @param file
     * @return
     * @throws Exception
     */
    private String analysis(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));
        HashMap hints = new HashMap<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        Result result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /*******************************************************以下是创建二维码提供的方法封装*******************************************************/

    /******************************另存为文件版本******************************/

    /**
     * 创建基础的二维码
     * @param content 二维码内容
     * @param destPath 存放路径
     * @throws Exception
     */
    public void create(String content, String destPath) throws Exception {
        generate(content, null, destPath, false);
    }

    /**
     * 创建带颜色基础的二维码
     * @param content 二维码内容
     * @param destPath 存放路径
     * @throws Exception
     */
    public void create(String content, String destPath,int frontColor,int backgroundColor) throws Exception {
        generate(content, null, destPath, false,frontColor,backgroundColor);
    }

    /**
     * 创建带图片的二维码
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param destPath 存放路径
     * @param needCompress 是否压缩图片
     * @throws Exception
     */
    public void create(String content, String imgPath, String destPath,boolean needCompress) throws Exception {
        generate(content, imgPath, destPath, needCompress);
    }

    /**
     * 创建带有自定义颜色和图片的二维码
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param destPath 存放路径
     * @param needCompress 是否压缩图片
     * @param frontColor 前景色
     * @param backgroundColor 背景色
     * @throws Exception
     */
    public void create(String content, String imgPath, String destPath,boolean needCompress,int frontColor,int backgroundColor) throws Exception {
        generate(content, imgPath, destPath, needCompress,frontColor,backgroundColor);
    }

    /******************************另存为文件版本******************************/

    /******************************Base64版本******************************/

    /**
     * 创建基础的二维码并返回Base64
     * @param content
     * @throws Exception
     */
    public String create(String content) throws Exception {
        return generateBase64(content,null,false);
    }

    /**
     * 创建带颜色基础的二维码并返回Base64
     * @param content
     * @throws Exception
     */
    public String create(String content,int frontColor,int backgroundColor) throws Exception {
        return generateBase64(content,null,false,frontColor,backgroundColor);
    }

    /**
     * 创建带图片的二维码并返回Base64
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @throws Exception
     */
    public String create(String content, String imgPath,boolean needCompress) throws Exception {
        return generateBase64(content, imgPath, needCompress);
    }

    /**
     * 创建带有自定义颜色和图片的二维码并返回Base64
     * @param content 二维码内容
     * @param imgPath 图片路径
     * @param needCompress 是否压缩图片
     * @param frontColor 前景色
     * @param backgroundColor 背景色
     * @throws Exception
     */
    public String create(String content, String imgPath,boolean needCompress,int frontColor,int backgroundColor) throws Exception {
        return generateBase64(content, imgPath, needCompress,frontColor,backgroundColor);
    }

    /******************************Base64版本******************************/

    /**
     * 根据文件路径解析二维码
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public String decode(String path) throws Exception {
        File file = new File(path);
        if(!file.exists()){
            throw new Exception("文件不存在!");
        }
        return analysis(file);
    }

}

四、使用示例

友情提醒:代码中的布尔值是代表Logo图片是否需要被压缩,如果是true说明嵌入的Logo图片需要被压缩,我的建议是默认为true,因为如果不压缩,在使用decode解析带Logo的二维码的时候会报com.google.zxing.NotFoundException的错误,博主亲自测试过。

单元测试:

java">@SpringBootTest
class EwmApplicationTests {

    @Resource
    private QRCodeUtil qrCodeUtil;

    @Test
    void contextLoads() throws Exception {

        qrCodeUtil.create("httstudy","F:\\基础二维码.jpg");
        qrCodeUtil.create("httstudy","F:\\带颜色的二维码.jpg",0xff0000,0xffff00);
        qrCodeUtil.create("httstudy","F:\\Logo.png","F:\\带logo的二维码.jpg",true);
        qrCodeUtil.create("httstudy","F:\\Logo.png","F:\\带颜色和logo的二维码.jpg",true,0xff0000,0xffff00);

        String str = qrCodeUtil.create("httstudy");
        String str2 = qrCodeUtil.create("httstudy",0xff0000,0xffff00);
        String str3 = qrCodeUtil.create("httstudy","F:\\Logo.png",true);
        String str4 = qrCodeUtil.create("httstudy","F:\\Logo.png",true,0xff0000,0xffff00);
        System.out.println(str);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);

        String result = qrCodeUtil.decode("F:\\基础二维码.jpg");
        String result2 = qrCodeUtil.decode("F:\\带颜色的二维码.jpg");
        String result3 = qrCodeUtil.decode("F:\\带logo的二维码.jpg");
        String result4 = qrCodeUtil.decode("F:\\带颜色和logo的二维码.jpg");
        System.out.println(result);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
    }

}

 运行结果:

五、Gitee源码

码云地址:SpringBoot生成二维码完整工具类分享

六、总结

良心博主原创封装不易,把常见场景需要用到的二维码类型都给大家封装好了,只要像单元测试那样一键生成就好了,如有问题,欢迎评论区留言!


http://www.niftyadmin.cn/n/4961010.html

相关文章

删除ubuntu开始菜单中的图标

背景 本来是很好看干净的界面 更新谷歌浏览器后出现了Gmail&#xff0c;幻灯片&#xff0c;谷歌硬盘等跟谷歌相关的乱七八糟东西搞得界面就很丑 解决问题 删掉那个图标 输入命令 sudo nautilus /usr/share/applicationssudo nautilus ~/.local/share/applications可以…

Failed to resolve: com.github.mcxtzhang:SwipeDelMenuLayout:V1.3.0

在allprojects下的repositories闭包里面添加jcenter()和maven {url https://jitpack.io}&#xff0c;具体可以看你的第三方框架需要添加什么仓库&#xff0c;大多数都只需要上面两个。 我的build.gradle&#xff08;Project&#xff09;完整内容如下&#xff1a; buildscript …

android NullPointerException externalCacheDir

先看代码&#xff1a; fun Context.getMyCacheDir(): String {return externalCacheDir!!.absolutePath "/my_cache" }如上代码&#xff0c;在某些手机可能会出现crash。 原因详细阅读api&#xff0c;注意他有一个大大的注解Nullable&#xff1a; Nullablepublic a…

2023年计算机设计大赛国三 数据可视化 (源码可分享)

2023年暑假参加了全国大学生计算机设计大赛&#xff0c;并获得了国家三等奖&#xff08;国赛答辩出了点小插曲&#xff09;。在此分享和记录本次比赛的经验。 目录 一、作品简介二、作品效果图三、设计思路四、项目特色 一、作品简介 本项目实现对农产品近期发展、电商销售、灾…

骨传导运动蓝牙耳机哪个牌子好?

生命在于运动&#xff0c;每次在运动时&#xff0c;搭配上音乐&#xff0c;可以极大程度让心情更为轻松和愉悦&#xff0c;可以说骨传导蓝牙耳机是爱运动的朋友的福音&#xff0c;相较于其他耳机来说&#xff0c;佩戴稳定不用担心出现脱落的情况&#xff0c;也不会出现传统耳机…

部署 Windows 域(一)

目录 简介 1. 部署 AD 前的准备 2. 部署 Windows 域的过程 2.1 安装域控制器 2.2 将客户机加入域 1.联机加入域 2.脱机加入域 简介 前面章节介绍了域的相关概念&#xff0c;以及工作组和域的主要区别&#xff0c;想要实现域环境&#xff0c;就必须部署至少一台域控制器。…

制作网络课堂学习平台(标签嵌套,后代选择器)

网络课堂学习平台 课程 1 这是课程 1 的描述。 模块 1 这是模块 1 的描述。 查看详情 模块 2 这是模块 2 的描述。 查看详情 课程 2 这是课程 2 的描述。 模块 1 这是块 2 的描述。 查看详情

机器学习笔记 - 使用 AugMix 增强图像分类模型的鲁棒性

一、简述 图像分类模型能够预测与训练数据具有相同分布的数据。然而,在现实场景中,输入数据可能会发生变化。例如,当使用不同的相机进行推理时,照明条件、对比度、颜色失真等可能与训练集不同,并显着影响模型的性能。为了应对这一挑战,Hendrycks 等人提出了 AugMix 算法。…