我需要根据数据库中的blob创建JSON。为了获得blob图像,我使用下面的代码并在json数组中显示之后:
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")); }我希望根据图像blob为每个图像返回一个JSON对象。我怎样才能实现它?
I to want return a JSON object for the each image according the image blob. How can I achieve it?
推荐答案JSON中的二进制数据通常最好用 Base64 - 编码表格。您可以使用提供的标准Java SE DatatypeConverter#printBase64Binary() 方法对Base64进行字节数组编码。
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);另一方只需对Base64进行解码即可。例如。在Android中,您可以使用内置的 android.util.Base64 此API。
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);更多推荐
如何用JSON表示数据库中的图像
发布评论