java 如何用 JSON 表示数据库中的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14897297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to represent an image from database in JSON
提问by Schlacter James
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 对象。我怎样才能实现它?
回答by BalusC
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);