java生成一维码并且在下面显示一维码内容
时间: 2024-05-03 21:20:14 浏览: 93
Java一维数组的声明初始化和引用-Java教程共2页.p
以下是Java生成一维码并在下方显示一维码内容的示例代码:
```java
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.commons.lang3.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class OneDimBarcodeGenerator {
public static void main(String[] args) {
String text = "One-dimensional barcode content";
try {
BufferedImage barcodeImage = generateOneDimBarcode(text);
// Display the barcode image and text in a JFrame
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame("One-dimensional Barcode");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(barcodeImage, 0, 0, null);
g.drawString(text, 50, 150);
}
};
frame.setContentPane(panel);
frame.setVisible(true);
});
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
public static BufferedImage generateOneDimBarcode(String text) throws WriterException, IOException {
// Set the barcode format and encoding hint
Code128Writer writer = new Code128Writer();
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// Generate the bit matrix and write it to an image
BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.CODE_128, 400, 200, hints);
BufferedImage barcodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
return barcodeImage;
}
}
```
该示例使用Google的ZXing库生成一维码,并在JFrame中显示一维码图像和下方的一维码内容。如果您想在控制台中显示一维码,可以简单地使用`System.out.println(text);`来打印一维码内容。
阅读全文