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());
    }
}
相关推荐
网安_秋刀鱼3 分钟前
【java安全】java安全基础
java·开发语言·安全·web安全
ZePingPingZe28 分钟前
不使用Spring事务的管理—原生JDBC实现事务管理
java·数据库·spring
吃喝不愁霸王餐APP开发者1 小时前
外卖API对接过程中时间戳与时区处理的最佳实践(避免核销失效)
java
抹除不掉的轻狂丶1 小时前
Java 日志框架完整指南:发展历史、核心组成与最佳实践
java·开发语言·python
林涧泣1 小时前
使用Java输出HelloWorld
java·开发语言
写代码的橘子n1 小时前
IPV6复习(基础入手版)
运维·服务器·网络
叫致寒吧1 小时前
Dockerfile
java·spring cloud·eureka
鸽鸽程序猿1 小时前
【刷题册】三
java·刷题
ruleslol1 小时前
java中调用uri请求的几种常见的方法
java
资生算法程序员_畅想家_剑魔1 小时前
Java常见技术分享-10-装饰器模式
java·开发语言·装饰器模式