qr code

42 阅读1分钟
/**
 * 生成带文本的二维码
 *
 * @param content 二维码包含的内容
 * @param text    二维码下方文字
 * @param width   二维码宽度
 * @param height  二维码高度 (height<=实际图片高度)
 * @return BufferedImage
 */
public static BufferedImage generateQRCodeWithText(String content, String text, int width, int height) {
    // 生成二维码图像
    BufferedImage qrImage = QrCodeUtil.generate(content, width, height);

    // 获取二维码有效底部的 Y 坐标
    int qrBottomY = ExportUtil.getQrCodeBottomY(qrImage);

    // 创建临时画布获取字体信息
    BufferedImage tempImg = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D tempG = tempImg.createGraphics();
    tempG.setFont(ExportUtil.getResourcesFont());
    FontMetrics fm = tempG.getFontMetrics();
    int ascent = fm.getAscent();
    int descent = fm.getDescent();
    int textWidth = fm.stringWidth(text);
    tempG.dispose();

    // 计算文字绘制基线的位置
    int padding = 4;
    int baselineY = qrBottomY + ascent + padding;

    // 生成新图像,高度适应文字
    int totalHeight = baselineY + descent;
    BufferedImage combined = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = combined.createGraphics();

    // 背景填充为白色
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, width, totalHeight);

    // 绘制二维码
    g.drawImage(qrImage, 0, 0, null);

    // 绘制文字
    g.setFont(ExportUtil.getResourcesFont());
    g.setColor(Color.BLACK);
    g.drawString(text, (width - textWidth) / 2, baselineY);
    g.dispose();

    return combined;
}