[英]How to convert barcode generated via barcode4j into base 64 in Java
我正在嘗試轉換通過條形碼4j生成的條形碼圖像,但無法這樣做。 當我使用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 :
您的問題在這一行:
String imgString = new String(Base64Encoder.encode(out.toByteArray()));
out.toByteArray()將輸出使用out.write()之前已寫入的字節
您可能想要這樣:
byte[] img = //canvas get bytes
String imgString = Base64.getEncoder().encodeToString(img);
您需要在調用out.toByteArray()
之前完成畫布。 這將刷新您在OutputStream上的條形碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.