自动化立体仓库 - WMS系统
#
luxiaotao1123
2020-07-01 c548ffe3cce99990138f81cca1ac8fdd46870f6e
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.zy.common.utils;
 
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.oned.Code128Writer;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
 
/**
 * 条形码工具
 * Created by vincent on 2020/6/6
 */
public class BarcodeUtils {
 
    private static final int DEFAULT_WIDTH = 100;
    private static final int DEFAULT_HEIGHT = 20;
 
    /**
     * 条形码编码
     */
    public static BufferedImage encode(String string){
        return encode(string, null, null);
    }
 
    public static BufferedImage encode(String string, Integer width, Integer height){
        try {
            Code128Writer writer = new Code128Writer();
            BitMatrix bar = writer.encode(string, BarcodeFormat.CODE_128, width==null?DEFAULT_WIDTH:width, height==null?DEFAULT_HEIGHT:height, new HashMap<>());
            return MatrixToImageWriter.toBufferedImage(bar);
        }
        catch (WriterException e){ throw new RuntimeException(e); }
    }
 
    /**
     * 条形码解码
     */
    public static String decode(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                throw new RuntimeException("the decode image may be not exit.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static void main(String[] args) {
        String imgPath = "F:/zxing_EAN-13.png";
        String contents = "6926557300360";
        int width = 105, height = 50;
        encode(contents, width, height);
        System.out.println("finished zxing EAN-13 encode.");
        String decodeContent = decode(imgPath);
        System.out.println("解码内容如下:" + decodeContent);
        System.out.println("finished zxing EAN-13 decode.");
    }
 
}