How to put byte stream image data into JSON object?

浪子不回头ぞ 提交于 2019-12-11 11:49:29

问题


I want to put multiple images in JSON object using byte stream format, i wrote the following code.

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();

I want to put encoded byte stream in myObj,but dont know how to do it.

Thanks


回答1:


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

I think this will work.




回答2:


Assuming you are using Java 8, and the javax.json package:

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();


来源:https://stackoverflow.com/questions/34574736/how-to-put-byte-stream-image-data-into-json-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!