0

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 :
Aniket
  • 3
  • 1
  • 7

2 Answers2

0

Your problem is in this line:

String imgString = new String(Base64Encoder.encode(out.toByteArray()));

out.toByteArray() will output the bytes you have written before using out.write()

you probably want this:

byte[] img = //canvas get bytes
String imgString = Base64.getEncoder().encodeToString(img);
Guilherme Mussi
  • 956
  • 7
  • 14
  • I tried below: byte[] imageData = canvas.toString().getBytes(); String imgString = java.util.Base64.getEncoder().encodeToString(imageData); It indeed generats some base64 string, but doesnot generate base64 for the barcode image which I am trying to get. – Aniket May 29 '18 at 14:22
  • Can you replace System.out.println("Generating Base64"); for System.out.println("Generating Base64 " + out.toByteArray().length); and tell me the result ? – Guilherme Mussi May 29 '18 at 15:44
0

You need to finish the canvas before calling: out.toByteArray(). This will flush your barcode on the OutputStream.

Deme
  • 209
  • 2
  • 9