Convert base64 string to Image in Java

I’m worried about that you need to decode only the base64 string to get the image bytes, so in your

"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVI..."

string, you must get the data after data:image\/png;base64,, so you get only the image bytes and then decode them:

String imageDataBytes = completeImageData.substring(completeImageData.indexOf(",")+1);

InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));

This is a code so you understand how it works, but if you receive a JSON object it should be done the correct way:

  • Converting the JSON string to a JSON object.
  • Extract the String under data key.
  • Make sure that starts with image/png so you know is a png image.
  • Make sure that contains base64 string, so you know that data must be decoded.
  • Decode the data after base64 string to get the image.

Leave a Comment