I have a string like (01)8638634367382(15)230316(3103)000998(10)45456465604 that I want to do it as barcode png using barcode4j lib in java. I use this code
// Create the barcode bean
Code128Bean barcode = new Code128Bean();
// Configure the barcode generator
final int dpi = 400;
barcode.setModuleWidth(0.2);
barcode.doQuietZone(false);
int codeset = Code128Constants.CODESET_C;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!Character.isDigit(c)) {
codeset = Code128Constants.CODESET_B;
break;
}
}
barcode.setCodeset(codeset);
// Generate the barcode bitmap
BitmapCanvasProvider canvas = new BitmapCanvasProvider(dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
barcode.generateBarcode(canvas, input);
try {
canvas.finish();
} catch (IOException e) {
throw new RuntimeException("Error generating barcode", e);
}
// Encode the bitmap as a base64 string
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(canvas.getBufferedImage(), "png", outputStream);
} catch (IOException e) {
throw new RuntimeException("Error encoding barcode as PNG", e);
}
byte[] barcodeBytes = outputStream.toByteArray();
String base64Barcode = Base64.getEncoder().encodeToString(barcodeBytes);
return base64Barcode;
but the generated barcode isn't recognisable by any barcode scanner software. Also I encode the image to base64 string and when I want to represent in any part of my program I decode it and show the image. Any idea what's wrong with this?
I expect to produce a readable barcode in this format (01)8638634367382(15)230316(3103)000998(10)45456465604 and of course it must be scannable by any software.
The example that you have supplied is a GS1 Application Identifier element string in bracketed representation.
Unless the library does it for you, you will need to convert this to unbracketed representation with FNC1 in first position, suitable for encoding directly into a Code 128. (It is this process that differentiates GS1-128 from plain Code 128.)
The bracketed AI element string that you provided —(01)8638634367382(15)230316(3103)000998(10)45456465604 — does not decode correctly:
Replacing the GTIN with one that is valid — (01)0101234567890128 — would allow you to represent the data in FNC1 in first syntax as "{FNC1}01012345678901281523031631030009981045456465604" which you will need to pass to the library as input in its expected format.
According to the barcode4j documentation the escape sequence particular to their software for encoding an FNC1 non-data character is a literal 0xF1 ASCII value:
More detail concerning the various representations of GS1 data is provided in this article.
GS1 provide the Barcode Syntax Resource which is a native library, with bindings for Java, that can process GS1 Application Identifier syntax data.