如何用JSON表示数据库中的图像

时间:2022-05-25 18:43:01

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:

我需要根据数据库中的blob创建JSON。要获取blob图像,我使用下面的代码并在json数组中显示之后:

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?

我希望根据图像blob为每个图像返回一个JSON对象。我怎样才能实现它?

1 个解决方案

#1


5  

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.

JSON中的二进制数据通常最好用Base64编码的形式表示。您可以使用标准Java SE提供的DatatypeConverter#printBase64Binary()方法对字节数组进行Base64编码。

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.

另一方只需对Base64进行解码即可。例如。在Android中,您可以使用内置的android.util.Base64 API。

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

#1


5  

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.

JSON中的二进制数据通常最好用Base64编码的形式表示。您可以使用标准Java SE提供的DatatypeConverter#printBase64Binary()方法对字节数组进行Base64编码。

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.

另一方只需对Base64进行解码即可。例如。在Android中,您可以使用内置的android.util.Base64 API。

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