0

我正在尝试转换通过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 :
4

2 回答 2

0

您的问题出在这一行:

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

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

你可能想要这个:

byte[] img = //canvas get bytes
String imgString = Base64.getEncoder().encodeToString(img);
于 2018-05-29T14:15:55.547 回答
0

您需要在调用之前完成画布:out.toByteArray()。这将刷新 OutputStream 上的条形码。

于 2018-08-15T16:41:38.137 回答