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());
    }
}
相关推荐
2601_962106641 分钟前
【无标题】
java·idea
汉吉龙测控技术4 分钟前
激光对中仪作用介绍(AS 激光对中仪)
java
Wang's Blog11 分钟前
Java 项目实战: 交友项目 - 完善用户信息章节复盘:套路清单与自检清单
java·dubbo·交友
用户31268748772013 分钟前
Java 11-21 新特性盘点:var、record、sealed、虚拟线程
java
TangGeeA14 分钟前
命令安全设置
java·服务器·安全
欣栀♡17 分钟前
Spring 循环依赖不止三级缓存,Boot 2.6 起这个开关默认已经关了
java·spring·缓存
SL_staff18 分钟前
3分钟上线新规则:业务人员拖拽完成合同超期自动暂停服务
java·mysql·全栈
Android小码家28 分钟前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle
范同学~28 分钟前
固定表头+第一列+最后一列
java·服务器·前端
雪落漂泊31 分钟前
Linux基础开发工具(三)gcc/g++与make/makefile篇
linux·运维·服务器