package com.zbooksoft.gdmis.common; 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 java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; /** * @Description: * @Author: zhai * @Date: 2025/8/15 **/ public class BarcodeGenerator { public static void generateBarcode(String data, String filePath) throws WriterException, IOException { // 设置条形码参数 Map hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 创建条形码生成器 Code128Writer barcodeWriter = new Code128Writer(); BitMatrix bitMatrix = barcodeWriter.encode(data, BarcodeFormat.CODE_128, 300, 100, hints); // 保存为图片文件 Path path = Paths.get(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } public static void main(String[] args) { try { String data = "Hello, World!"; String filePath = "D:\\barcode.png"; // generateBarcode(data, filePath); BufferedImage bufferedImage = generateBarcodeImage(data); System.out.println("条形码已生成:"); } catch (Exception e) { e.printStackTrace(); } } public static BufferedImage generateBarcodeImage(String data) throws WriterException { Map hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); Code128Writer barcodeWriter = new Code128Writer(); BitMatrix bitMatrix = barcodeWriter.encode(data, BarcodeFormat.CODE_128, 5, 5, hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } }