问题描述
我已经使用com.google.zxing
这个库生成了QR码。
QRCode的生成工作正常,但我想在QRcode下方显示QRcode的数据。
我想生成如下附件所示的QR码。
这是我的代码。
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data,BarcodeFormat.QR_CODE,width,height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"PNG",pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
解决方法
在这里,我生成了QR Code文件,并占用了内存,然后使用了图形库。 使用此库可以将文本添加到该内存中,然后再次保存。
public static void main(String[] args) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode("Hello world",BarcodeFormat.QR_CODE,300,300);
Path path = FileSystems.getDefault().getPath("test.png");
MatrixToImageWriter.writeToPath(bitMatrix,"PNG",path);
final BufferedImage image = ImageIO.read(new File(path.toString()));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(22f));
Color textColor = Color.BLACK;
g.setColor(textColor);
g.drawString("Hello world",15,300);
g.dispose();
ImageIO.write(image,"png",new File("test45.png"));
} catch (WriterException | IOException ex) {
}
}
,
在这里,我已经提供了完整的代码,用于生成是否带有文本的QRcode。
public byte[] generateQRCode(String data,Integer width,Integer height,String[] text) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(data,width,height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
// If text is needed to display
if (text.length > 0) {
int totalTextLineToadd = text.length;
InputStream in = new ByteArrayInputStream(pngData);
BufferedImage image = ImageIO.read(in);
BufferedImage outputImage = new BufferedImage(image.getWidth(),image.getHeight() + 25 * totalTextLineToadd,BufferedImage.TYPE_INT_ARGB);
Graphics g = outputImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,outputImage.getWidth(),outputImage.getHeight());
g.drawImage(image,image.getWidth(),image.getHeight(),null);
g.setFont(new Font("Arial Black",Font.BOLD,12));
Color textColor = Color.BLACK;
g.setColor(textColor);
FontMetrics fm = g.getFontMetrics();
int startingYposition = height + 5;
for(String displayText : text) {
g.drawString(displayText,(outputImage.getWidth() / 2) - (fm.stringWidth(displayText) / 2),startingYposition);
startingYposition += 20;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(outputImage,baos);
baos.flush();
pngData = baos.toByteArray();
baos.close();
}
return pngData;
} catch (WriterException | IOException ex) {
throw new ImtechoUserException(ex.getMessage(),0);
}
}
这将返回新生成的带有文本或不带文本的QR码的Byte []。
,@Ashish Khokhariya谢谢你我用你的代码 对不起,我无法“反馈”: 感谢您的反馈!记录名誉不足15人的选票,但不会更改公开显示的帖子分数。