How to represent an image from database in JSON How to represent an image from database in JSON json json

How to represent an image from database in JSON


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);

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);