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());
    }
}
相关推荐
灰原喜欢柯南6 分钟前
Spring Boot 自动配置全流程深度解析
java·spring boot·后端
Code_Artist11 分钟前
[Java并发编程]4.阻塞队列
java·数据结构·后端
poison_Program37 分钟前
使用 Prometheus 监控服务器节点:Node Exporter 详解与配置
运维·服务器·prometheus
心月狐的流火号44 分钟前
Java NIO Selector 源码分析
java
DebugKitty1 小时前
网络编程1-基本概念、函数接口
运维·服务器·网络·网络协议·socket·tcp
MrSYJ1 小时前
AuthenticationEntryPoint认证入口
java·spring cloud·架构
Mr. Cao code1 小时前
Nginx与Apache:Web服务器性能大比拼
运维·服务器·前端·nginx·apache
lssjzmn1 小时前
Java并发容器ArrayBlockingQueue与LinkedBlockingQueue对比PK
java·消息队列
用户98408905087242 小时前
Java基础之深拷贝浅拷贝-Integer
java
渣哥2 小时前
99%的人忽略了!Java Integer缓存池原来暗藏玄机
java