How to represent an image from database in JSON

别来无恙 提交于 2019-12-07 13:55:11

问题


I need to create JSON based on a blob from database. To get the blob image, I use the code below and after show in json array:

Statement s = connection.createStatement();
ResultSet r = s.executeQuery("select image from images");
while (r.next()) {
    JSONObject obj = new JSONObject();
    obj.put("img", r.getBlob("image"));
}

I to want return a JSON object for the each image according the image blob. How can I achieve it?


回答1:


Binary data in JSON is usually best to be represented in a Base64-encoded form. You could use the standard Java SE provided DatatypeConverter#printBase64Binary() method to Base64-encode a byte array.

byte[] imageBytes = resultSet.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
obj.put("img", imageBase64);

The other side has just to Base64-decode it. E.g. in Android, you could use the builtin android.util.Base64 API for this.

byte[] imageBytes = Base64.decode(imageBase64, Base64.DEFAULT);


来源:https://stackoverflow.com/questions/14897297/how-to-represent-an-image-from-database-in-json

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