【问题标题】:How to put byte stream image data into JSON object?如何将字节流图像数据放入 JSON 对象?
【发布时间】:2016-01-03 08:38:12
【问题描述】:

我想使用字节流格式将多个图像放入 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中,但不知道怎么做。

谢谢

【问题讨论】:

标签: java json image bytearray


【解决方案1】:
JSONObject myObj = new JSONObject();
myObj.put("1",encoder.encode(contents).getBytes());

我认为这会奏效。

【讨论】:

    【解决方案2】:

    假设您使用的是 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();
    

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2021-08-22
      • 2016-11-19
      • 2021-07-18
      • 2021-10-15
      相关资源
      最近更新 更多