2025-04-14 09:35:36 +08:00

45 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.cdzy.ebikeoperate.utils;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
/**
* 二维码生成工具类
*
* @author dingchao
* @date 2025/4/1
* @modified by:
*/
public class QRGenUtil {
/**
* 生成二维码并返回Base64编码
*
* @param content 二维码内容
* @return Base64编码的二维码
*/
public static String generateQRCodeBase64(String content) {
try (ByteArrayOutputStream stream = QRCode.from(content)
.withSize(300, 300) // 尺寸
.withErrorCorrection(ErrorCorrectionLevel.H) // 纠错等级H为最高
.to(ImageType.PNG) // 输出格式
.stream()) {
// 使用 Java 8+ 的 Base64 编码(避免自动换行问题)
return Base64.getEncoder().encodeToString(stream.toByteArray());
} catch (Exception e) {
throw new RuntimeException("生成二维码失败", e);
}
}
//public static void main(String[] args) {
// String content = "B726500590095"; // 二维码内容
// String base64 = generateQRCodeBase64(content);
// System.out.println("Base64 二维码: " + base64);
//}
}