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());
    }
}
相关推荐
a努力。2 分钟前
虾皮Java面试被问:JVM Native Memory Tracking追踪堆外内存泄漏
java·开发语言·jvm·后端·python·面试
学习是生活的调味剂13 分钟前
Java IO模型之BIO和NIO分析
java·nio
Web极客码16 分钟前
释放WordPress磁盘空间并减少Inode使用量
服务器·数据库·ubuntu
笙枫21 分钟前
基于AI Agent框架下的能源优化调度方案和实践 |工具函数介绍(详细)
java·人工智能·能源
我命由我1234523 分钟前
Android Studio - Android Studio 去除 import 的未使用的类
android·java·ide·学习·java-ee·android studio·学习方法
沛沛老爹27 分钟前
Skills高级设计模式(一):向导式工作流与模板生成
java·人工智能·设计模式·prompt·aigc·agent·web转型
程序员老徐29 分钟前
Tomcat源码分析二(Tomcat启动源码分析)
java·tomcat·firefox
BD_Marathon32 分钟前
SpringMVC——5种类型参数传递
android·java·数据库
✧˖‹gσσ∂ иιghт›✧32 分钟前
esp32 s3 修改本地ip和服务器IP
服务器·网络协议·tcp/ip
Ares-Wang33 分钟前
网络》》防火墙
运维·服务器·网络