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



我需要基于数据库中的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"));
}

我想根据图像blob为每个图像返回一个JSON对象。我怎样才能做到这一点?

JSON中的二进制数据通常最好以Base64编码的形式表示。您可以使用Java SE提供的标准DatatypeConverter#printBase64Binary()方法对字节数组进行Base64编码。
byte[] imageBytes = resultSet.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
obj.put("img", imageBase64);

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

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

最新更新