0

I am encoding an image in the following way and store it in my database:

 public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

Now I am trying to decode it in the following way and display it in an ImageView :

  try{
        InputStream stream = new ByteArrayInputStream(image.getBytes());
        Bitmap bitmap = BitmapFactory.decodeStream(stream);
        return bitmap;
    }
    catch (Exception e) {
        return null;
    }

}

However the ImageView remains blank and the image is not displayed. Am I missing something?

1 Answer 1

2

Try decoding the string first from Base64.

 public static Bitmap decodeBase64(String input) {
        byte[] decodedByte = Base64.decode(input, 0);
        return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
 }

In you case:

 try{
        byte[] decodedByte = Base64.decode(input, 0);
        InputStream stream = new ByteArrayInputStream(decodedByte);
        Bitmap bitmap = BitmapFactory.decodeStream(stream);
        return bitmap;
    }
    catch (Exception e) {
        return null;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Are you saying I should do this instead of my try/catch block or in addition to it?
It works when I simply replace the try catch with the code you provided :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.