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());
    }
}
相关推荐
一条泥憨鱼2 分钟前
【Redis | 黑马点评】基于Redis的消息队列 | stream消息队列 源码解读
java·数据库·redis·缓存·lua
aibo8603086 分钟前
基于 Spring Boot + Vue3 的博物馆藏品管理系统设计与实现
java·spring boot·后端
fanruitian10 分钟前
python 进程 线程
java·前端·python
\光辉岁月/13 分钟前
javaSE8-新特性-Stream&Option
java·stream·option
zzu123zsw17 分钟前
把条件校验收敛到枚举接口:Spring Boot 统一断言模式与零污染异常切面工程化
java·spring boot·后端·架构设计
SL_staff20 分钟前
计划系统落地难?从开发者视角重构执行入口体验
java·开源·全栈
小胡202423 分钟前
DzzOffice V2.4.2 版本上线!安全加固 × 网盘体验全面升级
服务器·bootstrap·php·协同办公·dzzoffice
伯恩bourne37 分钟前
Reactive Streams 出现的原因
服务器·网络
叼烟扛炮41 分钟前
Linux 学习笔记(九):自动化构建神器 Make 与 Makefile
linux·运维·服务器
鬼手点金43 分钟前
单轮对话:最简单的 API 调用
java·服务器·前端·javascript·react.js·servlet·tomcat