zxing生成的二维码并带有底部文字
要生成带有底部文字的二维码,可以使用zxing库的Java API。下面是一个示例代码:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCodeGenerator {
public static void main(String[] args) {
String text = "https://example.com";
String bottomText = "Scan QR code for more information";
int width = 300;
int height = 300;
String format = "png";
String filePath = "qrcode_with_text.png";
// Set QR code parameters
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix;
try {
bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
} catch (WriterException e) {
e.printStackTrace();
return;
}
// Create BufferedImage object to draw QR code and text
BufferedImage image = new BufferedImage(width, height + 30, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setColor(Color.WHITE);
graphics2D.fillRect(0, 0, width, height + 30);
graphics2D.setColor(Color.BLACK);
// Draw QR code
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)) {
graphics2D.fillRect(x, y, 1, 1);
}
}
}
// Draw bottom text
graphics2D.setFont(new Font("Arial", Font.PLAIN, 12));
int textWidth = graphics2D.getFontMetrics().stringWidth(bottomText);
int textHeight = graphics2D.getFontMetrics().getHeight();
int textX = (width - textWidth) / 2;
int textY = height + (30 - textHeight) / 2;
graphics2D.drawString(bottomText, textX, textY);
// Save QR code image with bottom text
try {
ImageIO.write(image, format, new File(filePath));
System.out.println("QR code with bottom text generated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
请确保你已经将zxing库添加到你的Java项目中。运行上面的代码后,将生成一个名为"qrcode_with_text.png"的带有底部文字的二维码图片
原文地址: https://www.cveoy.top/t/topic/iQfX 著作权归作者所有。请勿转载和采集!