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());
    }
}
相关推荐
wanhengidc1 分钟前
云真机和云手机的区别
运维·服务器·游戏·智能手机·云计算
yewq-cn14 分钟前
海思 SLE 芯片 Linux 烧录
linux·服务器
♡喜欢做梦17 分钟前
Spring MVC 响应处理:页面、数据与状态配置详解
java·javascript·spring·java-ee
计算机学姐20 分钟前
基于SpringBoot的公务员考试管理系统【题库组卷+考试练习】
java·vue.js·spring boot·后端·java-ee·intellij-idea·mybatis
顾安r21 分钟前
11.5 脚本 本地网站收藏(解封归来)
linux·服务器·c语言·python·bash
HahaGiver66627 分钟前
Unity与Android原生交互开发入门篇 - 打开Android的设置
android·java·unity·游戏引擎·android studio
Blossom.11828 分钟前
把AI“贴”进路灯柱:1KB决策树让老旧路灯自己报「灯头松动」
java·人工智能·python·深度学习·算法·决策树·机器学习
C# 学习者40 分钟前
C# 为异步函数实现WaitAsync方法
java·前端·c#
❀͜͡傀儡师41 分钟前
快速定位并解决Java应用CPU占用过高问题
java·开发语言·python
zzzsde44 分钟前
【Linux】权限(1):初识权限与使用理解
linux·运维·服务器