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

时间:2018-05-29 14:01:57

标签: java base64 barcode4j

我正在尝试转换通过barcode4j生成的条形码图像但无法这样做。当我使用FileOutputStream在本地路径中生成图像时,它按预期工作。但是当使用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();
    }
    }
}

输出

Generating Base64
String Generated :

2 个答案:

答案 0 :(得分:0)

你的问题在这一行:

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

out.toByteArray()将输出您在使用out.write()之前编写的字节

你可能想要这个:

byte[] img = //canvas get bytes
String imgString = Base64.getEncoder().encodeToString(img);

答案 1 :(得分:0)

您需要先完成画布,然后再调用: <div class="card text-center"> <img class="card-img-top mx-auto d-block" style="max-width: 100%;"> <div class="card-body d-flex flex-column align-items-center"> <h5 class="card-title">AKRACING Nitro Gaming Racestoel - Wit</h5> <p class="mt-auto">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="mt-auto btn btn-danger">€ 279,-</a> </div> </div> 。 这将刷新您在OutputStream上的条形码。