如何使用Java生成带有上下文本的二维码?
解决方案:生成带上下文本的二维码
我之前也处理过类似的需求,其实只要把Zxing生成的二维码和自定义文本绘制到同一个画布中就能实现。下面是修改后的完整代码,我会给你标注关键步骤:
import java.io.File; import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; public class Create_QR { public static void main(String[] args) { try { // 二维码核心内容 String qrCodeData = "This is the text"; // 上下自定义文本 String topText = "用户名: Thilinna Nirmal"; String bottomText = "活动名称: 技术交流沙龙"; String filePath = "C:\\Users\\Nirmalw\\Desktop\\Projects\\QR\\test\\test_img\\my_QR.png"; String charset = "UTF-8"; // 二维码基础配置 Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); BitMatrix matrix = new MultiFormatWriter().encode( new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, 500, 500, hintMap); // 1. 获取二维码的BufferedImage对象(不直接写入文件,留作后续编辑) BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix); int qrWidth = qrImage.getWidth(); int qrHeight = qrImage.getHeight(); // 2. 创建新画布,预留上下文本区域(这里设置每个文本区域高度为60像素) int textAreaHeight = 60; int newImageWidth = qrWidth; int newImageHeight = qrHeight + textAreaHeight * 2; BufferedImage finalImage = new BufferedImage(newImageWidth, newImageHeight, BufferedImage.TYPE_INT_RGB); // 3. 初始化绘图工具,填充白色背景 Graphics2D g2d = finalImage.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, newImageWidth, newImageHeight); // 4. 将二维码绘制到画布中间位置(顶部留出文本区域) g2d.drawImage(qrImage, 0, textAreaHeight, null); // 5. 设置文本样式,绘制上下居中的文本 g2d.setColor(Color.BLACK); Font textFont = new Font("Arial", Font.BOLD, 18); g2d.setFont(textFont); FontMetrics metrics = g2d.getFontMetrics(textFont); // 绘制顶部文本(水平居中计算:(画布宽度-文本宽度)/2) int topTextX = (newImageWidth - metrics.stringWidth(topText)) / 2; int topTextY = textAreaHeight / 2 + metrics.getAscent() / 2; g2d.drawString(topText, topTextX, topTextY); // 绘制底部文本 int bottomTextX = (newImageWidth - metrics.stringWidth(bottomText)) / 2; int bottomTextY = textAreaHeight + qrHeight + (textAreaHeight / 2 + metrics.getAscent() / 2); g2d.drawString(bottomText, bottomTextX, bottomTextY); // 释放绘图资源 g2d.dispose(); // 6. 将合成后的图片写入指定路径 ImageIO.write(finalImage, "png", new File(filePath)); System.out.println("带文本的QR Code创建成功!"); } catch (Exception e) { System.err.println("生成失败: " + e.getMessage()); e.printStackTrace(); } } }
关键逻辑说明:
- 保留二维码编辑权限:用
MatrixToImageWriter.toBufferedImage(matrix)获取二维码图片对象,而不是直接写入文件,方便后续合成文本。 - 扩展画布空间:根据二维码尺寸,额外添加上下文本区域的高度,确保文本有足够显示空间。
- 文本居中处理:通过
FontMetrics计算文本宽度,再结合画布宽度算出水平居中的坐标,让文本始终对齐二维码中心。 - 样式自定义:你可以根据需求调整文本的字体、大小、颜色,或者修改文本区域的高度,适配不同的设计要求。
内容的提问来源于stack exchange,提问作者Thilinna Nirmal
相关产品推荐
相关产品推荐

