84 lines
2.9 KiB
Java
84 lines
2.9 KiB
Java
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 javax.imageio.ImageIO;
|
||
import java.awt.*;
|
||
import java.awt.image.BufferedImage;
|
||
import java.io.ByteArrayInputStream;
|
||
import java.io.ByteArrayOutputStream;
|
||
import java.util.Base64;
|
||
|
||
/**
|
||
* 二维码生成工具类
|
||
*
|
||
* @author dingchao
|
||
* @date 2025/4/1
|
||
* @modified by:
|
||
*/
|
||
public class QRGenUtil {
|
||
|
||
/**
|
||
* 生成二维码并返回Base64编码
|
||
* <p>增加内容文字
|
||
*
|
||
* @param content 二维码内容
|
||
* @param text 文字内容
|
||
* @return Base64编码的二维码
|
||
*/
|
||
public static String generateQRCodeBase64(String content, String text) {
|
||
// 1. 生成基础二维码
|
||
try (ByteArrayOutputStream qrStream = QRCode.from(content)
|
||
.withSize(300, 300)
|
||
.withCharset("UTF-8")
|
||
.withErrorCorrection(ErrorCorrectionLevel.H) // 纠错等级(H为最高)
|
||
.to(ImageType.PNG) // 输出格式
|
||
.stream()) {
|
||
if(text == null || text.isEmpty()){
|
||
return Base64.getEncoder().encodeToString(qrStream.toByteArray());
|
||
}
|
||
|
||
// 2. 将二维码转换为 BufferedImage
|
||
ByteArrayInputStream inputStream = new ByteArrayInputStream(qrStream.toByteArray());
|
||
BufferedImage qrImage = ImageIO.read(inputStream);
|
||
|
||
// 3. 创建新 BufferedImage 并绘制文字
|
||
BufferedImage finalImage = new BufferedImage(
|
||
qrImage.getWidth(), qrImage.getHeight()+ 20, // 增加文字区域高度,
|
||
BufferedImage.TYPE_INT_ARGB
|
||
);
|
||
Graphics2D g2d = finalImage.createGraphics();
|
||
g2d.drawImage(qrImage, 0, 0, null);
|
||
|
||
// 设置文字样式
|
||
g2d.setFont(new Font("Arial", Font.BOLD, 20));
|
||
g2d.setColor(Color.BLACK);
|
||
|
||
// 计算文字位置(底部居中)
|
||
int textWidth = g2d.getFontMetrics().stringWidth(text);
|
||
int x = (qrImage.getWidth() - textWidth) / 2;
|
||
int y = qrImage.getHeight() - 2; // 底部留白
|
||
|
||
// 添加文字说明
|
||
g2d.drawString(text, x, y);
|
||
g2d.dispose();
|
||
|
||
// 使用 Java 8+ 的 Base64 编码(避免自动换行问题)
|
||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||
ImageIO.write(finalImage, "PNG", stream);
|
||
return Base64.getEncoder().encodeToString(stream.toByteArray());
|
||
} catch (Exception e) {
|
||
throw new RuntimeException("生成二维码失败", e);
|
||
}
|
||
}
|
||
|
||
//public static void main(String[] args) {
|
||
// String content = "B72650"; // 二维码内容
|
||
// String base64 = generateQRCodeBase64(content);
|
||
// System.out.println("Base64 二维码: " + base64);
|
||
//}
|
||
|
||
}
|