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());
    }
}
相关推荐
驭渊的小故事21 分钟前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
速捷工控 PLC触摸屏还原程序2 小时前
欧姆龙NB上传密码忘了,换屏前怎么保留原程序?
运维·服务器·欧姆龙
文丑颜不良啊2 小时前
LeetCode3001~3020题目解析
java·leetcode
爱勇宝3 小时前
SSL 证书别再手动续了:acme.sh + Let's Encrypt + 云厂商 DNS 全自动实战
运维·服务器
山楂树の3 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
.痞老板.5 小时前
java ee--文件操作和IO
java·java-ee
简 洁 冬冬5 小时前
分页「向上取整」公式 `(total + size - 1) / size` 的完整推导
java·分页
wacsii5 小时前
【Linux进程(五)】进程控制全解析:从创建、终止、等待到程序替换
linux·服务器
七夜zippoe6 小时前
Nexent Linux 部署:用 deploy.sh
linux·服务器·docker·部署·ai智能体·nexent
去码头整点薯条986 小时前
NFS服务器
linux·运维·服务器