2016-01-03 33 views
0

我想使用字节流格式在JSON对象中放置多个图像,我写了下面的代码。如何将字节流图像数据放入JSON对象?

FileInputStream fin = new FileInputStream(pathToImages+"//"+"01.jpg"); 

     BufferedInputStream bin = new BufferedInputStream(fin); 

     BufferedOutputStream bout = new BufferedOutputStream(out); 
     int ch =0; ; 

     sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder(); 
     byte[] contents = new byte[5000000]; 
     int bytesRead = 0; 
     String strFileContents; 
     while ((bytesRead = bin.read(contents)) != -1) { 
      bout.write(encoder.encode(contents).getBytes()); 
     } 
JsonObject myObj = new JsonObject(); 

我想把编码的字节流放在myObj中,但不知道该怎么做。

感谢

+1

如果你是在Java的8,您可能需要使用https://docs.oracle.com/javase/8/docs/改为使用api/java/util/Base64.html。 – Henry

回答

0
JSONObject myObj = new JSONObject(); 
myObj.put("1",encoder.encode(contents).getBytes()); 

我认为这会工作。

1

假设你正在使用Java 8,javax.json包:

Path path = Paths.get(pathToImages, "01.jpg"); 

ByteArrayOutputStream bytes = new ByteArrayOutputStream(
    (int) (Files.size(path) * 4/3 + 4)); 

try (OutputStream base64Stream = Base64.getEncoder().wrap(bytes)) { 
    Files.copy(path, base64Stream); 
} 

String base64 = bytes.toString("US-ASCII"); 

JsonObjectBuilder builder = Json.createObjectBuilder(); 
builder.add("data", base64); 

JsonObject myObj = builder.build();