简体   繁体   English

如何将通过条形码4j生成的条形码转换为Java中的base 64

[英]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. 我正在尝试转换通过条形码4j生成的条形码图像,但无法这样做。 When I use FileOutputStream to generate image in local path its working as expected. 当我使用FileOutputStream在本地路径中生成图像时,其工作正常。 but when using ByteArrayOutputStream to convert it into base64 string I am getting nothing.. Is there something wrong with my code? 但是当使用ByteArrayOutputStream将其转换为base64字符串时,我什么也没得到。.我的代码有问题吗?

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() out.toByteArray()将输出使用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() . 您需要在调用out.toByteArray()之前完成画布。 This will flush your barcode on the OutputStream. 这将刷新您在OutputStream上的条形码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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