要在zxing生成的二维码图片下方加文字,可以使用Java的Graphics2D类来实现。以下是一个示例代码:

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class QRCodeWithText {
    public static void main(String[] args) {
        String qrCodeFilePath = "path/to/your/qrcode.png";
        String text = "Your text here";
        
        try {
            BufferedImage qrCodeImage = ImageIO.read(new File(qrCodeFilePath));
            
            // 创建一个带有文本的新图片
            int width = qrCodeImage.getWidth();
            int height = qrCodeImage.getHeight() + 30; // 加上30像素的高度来容纳文本
            BufferedImage imageWithText = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = imageWithText.createGraphics();
            graphics.drawImage(qrCodeImage, 0, 0, null);
            
            // 设置文本样式
            Font font = new Font("Arial", Font.PLAIN, 16);
            graphics.setFont(font);
            graphics.setColor(Color.BLACK);
            
            // 将文本居中写入图片
            FontMetrics fontMetrics = graphics.getFontMetrics(font);
            int textWidth = fontMetrics.stringWidth(text);
            int textHeight = fontMetrics.getHeight();
            int textX = (width - textWidth) / 2;
            int textY = height - textHeight + fontMetrics.getAscent();
            graphics.drawString(text, textX, textY);
            
            // 保存图片
            String outputFilePath = "path/to/your/output/image.png";
            ImageIO.write(imageWithText, "png", new File(outputFilePath));
            
            System.out.println("QR code image with text successfully generated!");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,首先读取zxing生成的二维码图片。然后创建一个新的BufferedImage对象,该对象的宽度和高度与二维码图片相同,但高度增加了30像素,以容纳文本。接下来,使用Graphics2D类的drawImage方法将二维码图片绘制到新图片上。然后设置文本样式,并使用drawString方法将文本居中写入新图片。最后,使用ImageIO类的write方法将带有文本的图片保存到指定路径。

请将代码中的"path/to/your/qrcode.png"替换为zxing生成的二维码图片的文件路径,将"Your text here"替换为要添加的文本,将"path/to/your/output/image.png"替换为要保存图片的输出路径。运行代码后,将会生成带有文本的二维码图片

zxing生成的二维码图片下方加文字

原文地址: https://www.cveoy.top/t/topic/iQfa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录