How to represent an image from a database to JSON

I need to generate a blob based JSON from a database. To get the blob image I use below code and after showing 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"));
}

      

I need to return a JSON object for each image by image frame. How can I achieve this?

+3


source to share


1 answer


Binary data in JSON is usually best represented in Base64- encoded form. You can use standard Java SE, provided DatatypeConverter#printBase64Binary()

the Base64-encode method is a byte array.

byte[] imageBytes = resultSet.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
obj.put("img", imageBase64);

      



The other side only has Base64 decoding. For example. on android you can use the built-in android.util.Base64

API to do this.

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

      

+5


source







All Articles