java 生成一维码并打印

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是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);`来打印一维码内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值