Converting Images to JSON Objects

This is a short tutorial which covers converting Images to JSON Objects and vice-versa.

This approach can be used to store Images into Database as a JSON String.

There are two steps involved in converting from Image(Bitmap) to JSON:

  1. Converting Image(Bitmap) to String
  2. Converting String to JSON

1>  Converting Image to String:

The following snippet converts the IMAGE to a STRING

private String getStringFromBitmap(Bitmap bitmapPicture) {
 * This functions converts Bitmap picture to a string which can be
 * JSONified.
 * */
 final int COMPRESSION_QUALITY = 100;
 String encodedImage;
 ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
 bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
 byte[] b = byteArrayBitmapStream.toByteArray();
 encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
 return encodedImage;

2> Converting String to JSON:

Getting JSON object from String with the key as “image”

String encodedImage = getStringFromBitmap(bitmapPicture);
JSONObject jsonObj = new JSONObject("{\"image\":\" + encodedImage + \"}");

As expected the reverse process (JSON to Image) also involves the following two process:

  1. Converting JSON to String
  2. Converting String to Image(Bitmap)

1>  Converting JSON  to String:

Get String corresponding to the Key “image”

String jsonString = jsonObj.getString("image");

2>  Converting String  to Image:

This snippet gets back the Bitmap image from the String

private Bitmap getBitmapFromString(String jsonString) {
* This Function converts the String back to Bitmap
* */
byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;

I hope this tutorial was helpful.

Switch to our mobile site