多单位版国产化地质资料管理系统
zs
2025-12-18 4f0d9bde31a80f6279e26466250da7716eec627f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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<EncodeHintType, Object> 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<EncodeHintType, Object> 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);
    }
}