修改完善二维码生成,增加内容文字
This commit is contained in:
parent
d88bfd6a48
commit
37050662ec
@ -4,6 +4,10 @@ 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;
|
||||
|
||||
@ -18,17 +22,48 @@ public class QRGenUtil {
|
||||
|
||||
/**
|
||||
* 生成二维码并返回Base64编码
|
||||
* <p>增加内容文字
|
||||
*
|
||||
* @param content 二维码内容
|
||||
* @return Base64编码的二维码
|
||||
*/
|
||||
public static String generateQRCodeBase64(String content) {
|
||||
try (ByteArrayOutputStream stream = QRCode.from(content)
|
||||
.withSize(300, 300) // 尺寸
|
||||
// 1. 生成基础二维码
|
||||
try (ByteArrayOutputStream qrStream = QRCode.from(content)
|
||||
.withSize(300, 300)
|
||||
.withCharset("UTF-8")
|
||||
.withErrorCorrection(ErrorCorrectionLevel.H) // 纠错等级(H为最高)
|
||||
.to(ImageType.PNG) // 输出格式
|
||||
.stream()) {
|
||||
|
||||
// 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(content);
|
||||
int x = (qrImage.getWidth() - textWidth) / 2;
|
||||
int y = qrImage.getHeight() - 2; // 底部留白
|
||||
|
||||
// 添加文字说明
|
||||
g2d.drawString(content, 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);
|
||||
@ -36,7 +71,7 @@ public class QRGenUtil {
|
||||
}
|
||||
|
||||
//public static void main(String[] args) {
|
||||
// String content = "B726500590095"; // 二维码内容
|
||||
// String content = "B72650"; // 二维码内容
|
||||
// String base64 = generateQRCodeBase64(content);
|
||||
// System.out.println("Base64 二维码: " + base64);
|
||||
//}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user