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());
    }
}
相关推荐
i220818 Faiz Ul8 分钟前
药店管理|基于springboot + vue药店管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·美食分享系统
不吃土豆的马铃薯13 分钟前
C++ 正则表达式入门详解
linux·服务器·网络·数据库·c++·正则表达式
满怀冰雪14 分钟前
第15篇-链表基础-反转链表-合并链表与快慢指针
java·算法·链表
番茄去哪了22 分钟前
RabbitMQ
java·rabbitmq·java-rabbitmq
西凉的悲伤23 分钟前
redis-windows 安装 redis 到 windows 电脑
java·windows·redis·redis-windows
starsky7623824 分钟前
NIO与BIO的区别
java·服务器·nio
caimouse30 分钟前
Reactos 第 8 章 结构化异常处理 — 8.4 软异常
服务器·开发语言·windows
满怀冰雪30 分钟前
第14篇-队列与单调队列-解决窗口最值问题的关键结构
java·算法
方便面不加香菜31 分钟前
Linux--基础IO(二)
linux·运维·服务器
艾莉丝努力练剑38 分钟前
【Linux网络】NAT、内网穿透、内网打洞
linux·运维·服务器·网络·计算机网络·udp·php