如何用JSON表示数据库中的图像 [英] How to represent an image from database in JSON

查看:774
本文介绍了如何用JSON表示数据库中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据数据库中的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表示数据库中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆