简体   繁体   中英

How to convert barcode generated via barcode4j into base 64 in Java

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:

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM