Java生成二维码——附Utils工具类

参加2023年的计算机设计大赛国赛,拿到了一等奖。

现在将项目中的工具类代码剥离出来,方便之后项目开发中复用。

实现效果:

代码实现:

java 复制代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Base64;
import java.util.HashMap;

/**
 * @Author: KMHRKFC
 * @Date: 2022/7/11 20:44
 */
public class QRCodeUtils {

    private static int width = 600;
    private static int height = 600;
    private static String format = "png";
    private static HashMap hints;

    static {
        hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");   // 设置字符集, utf-8
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);     // 设置容错率
        hints.put(EncodeHintType.MARGIN, 1);                // 设置边距空白宽度为1
    }

    public static String str2QRCode(String content) {
        FastByteArrayOutputStream os = null;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            os = new FastByteArrayOutputStream();
            ImageIO.write(image, format, os);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray());
    }
}
相关推荐
bkspiderx13 分钟前
C++符号冲突与内部符号优先策略详解
linux·服务器·c++·符号冲突·内部符号
tz52538 分钟前
Superpowers 游戏开发实战应用场景大纲
linux·运维·服务器
两点王爷2 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
悟道书生3 小时前
hashMap/hashSet/hashCode详解
java
nice_lcj5205 小时前
依赖注入的三种方式:构造器、Setter、字段怎么选
java·spring·面试·依赖注入·字段注入·构造器注入
噢,我明白了5 小时前
实际项目导出方式应用
java·状态模式·导出
جيون داد ناالام ميづ6 小时前
七、MyBatis 源码剖析:核心流程拆解(初始化 + SQL 执行)
java·sql·mybatis
如夏倾城6 小时前
大模型(Large Model)解析:从数据类型、模型架构到任务选型
服务器·网络·数据库·语言模型·架构·audiolm
ClkLog-开源埋点用户分析6 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言