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());
    }
}
相关推荐
chuan.bai3 小时前
Java RAG 实战(第 11 篇):RAG 知识工作台网页
java·开发语言·人工智能
0x535 小时前
网站通信(一)
java
Terra.K6 小时前
Java异常学习[特殊字符]
java·开发语言·学习
三言老师6 小时前
K8s集群运行时自动化运维全覆盖落地实操(下)
linux·运维·服务器·网络
葡萄城技术团队7 小时前
InfluxDB 2\.x 深度解析:核心架构、Flux 函数与制造业落地指南(三)
java·开发语言·架构
Super 含7 小时前
Android 启动优化(五):线程、GC 与 IO 为什么会拖慢启动?
java·服务器·数据库
counting money7 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
程序员小八7778 小时前
上海百度B端java后端日常实习一面
java·开发语言
土星云SaturnCloud8 小时前
产线SOP动作级AI监管方案:土星云SE110S-WC8赋能合规识别、预警与效率分析
大数据·服务器·人工智能·ai·边缘计算
躺不平的理查德9 小时前
嵌入式 Linux 系统移植与 SD 卡量产镜像制作
linux·运维·服务器