Search code examples
javabarcode

Why do identical data barcodes look different visually?


I'm encountering a discrepancy between two barcodes with identical content but different raw bytes. One barcode is generated using an online tool called Labelary, designed for creating ZPL Labels, and the other is generated in my Java code using the ZXing library. Despite having the same content, the visual appearance of the barcodes differs.

My Barcode

My barcode

Raw text: 12345678
Raw bytes: 69 0c 22 38 4e 2f 6a

BarcodeGenerator.java

public byte[] getBarCode128(String data, int width, int height) {
    Code128Writer writer = new Code128Writer();
    BitMatrix matrix = writer.encode(data, BarcodeFormat.CODE_128, width, height);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {
        MatrixToImageWriter.writeToStream(matrix, "png", outputStream);
        return outputStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Main.java

public static void main(String[] args) {
    String data = "12345678";
        
    int width = (int) (data.length() * 11 * moduleWidth);
    int height = 270;
        
    BarcodeGenerator barcode = new BarcodeGenerator();
    byte[] barcodeImageBytes = barcode.getBarCode128(data, (int) width, (int) height);
}

Barcode from Labelary

Click here to view source code.

Barcode from Labelary

Raw text: 12345678
Raw bytes: 68 11 12 13 14 15 16 17 18 3c 6a

What could be the potential reasons for this discrepancy, and how can I ensure correct barcode generation using the ZXing library in Java?


Solution

  • Both are correct, just different encodings. The 69 one is Code C with two digits per code point. The longer 68 one is Code B.

    See also: https://en.wikipedia.org/wiki/Code_128

    If you want to force your code to also do the longer code B, you could set the FORCE_CODE_SET encode hint to "B".

    Wild guess about the encode hints:

    Map<EncodeHintType, String> hints = new HashMap<>();
    hints.put(EncodeHintType.FORCE_CODE_SET, "B");
    BitMatrix matrix = writer.encode(data, BarcodeFormat.CODE_128, width, height, hints);