I am trying to convert barcode image generated via barcode4j but unable to do so. When I use FileOutputStream to generate image in local path its working as expected. but when using ByteArrayOutputStream to convert it into base64 string I am getting nothing.. Is there something wrong with my code?
public void testNothing() throws FileNotFoundException, UnsupportedEncodingException{
Code39Bean bean = new Code39Bean();
int resolution = 150;
bean.setModuleWidth(UnitConv.in2mm(1.0f / resolution)); //makes the narrow bar
bean.setWideFactor(3);
bean.doQuietZone(false);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
BitmapCanvasProvider canvas = new BitmapCanvasProvider(
out, "image/x-png", resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
bean.generateBarcode(canvas, "1234");
System.out.println("Generating Base64");
// Base64Encoder encode= new Base64Encoder();
String imgString = new String(Base64Encoder.encode(out.toByteArray()));
System.out.println("String Generated :"+ imgString);
try {
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
canvas.finish();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
Generating Base64
String Generated :
Your problem is in this line:
out.toByteArray() will output the bytes you have written before using out.write()
you probably want this: