I have a Base64 String that represents a BitMap image.
I need to transform that String into a BitMap image again to use it on a ImageView in my Android app
How to do it?
This is the code that I use to transform the image into the base64 String:
//proceso de transformar la imagen BitMap en un String: //android:src="c:\logo.png" Resources r = this.getResources(); Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object byte b = baos.toByteArray(); //String encodedImage = Base64.encode(b, Base64.DEFAULT); encodedImage = Base64.encodeBytes(b);
You can just basically revert your code using some other built in methods.
byte decodedString = Base64.decode(encodedImage, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
To anyone who is still interested in this question: If: 1-decodeByteArray returns null 2-Base64.decode throws bad-base64 Exception
Here is the solution: -You should consider the value sent to you from API is Base64 Encoded and should be decoded first in order to cast it to a Bitmap object! -Take a look at your Base64 encoded String, If it starts with
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:
final String encodedString = "data:image/jpg;base64, ...."; final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",") + 1);
Now the pureBase64Encoded object is ready to be decoded:
final byte decodedBytes = Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Now just simply use the line below to turn this into a Bitmap Object! :
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.length);
Or if you're using the great library Glide:
This should do the job! It wasted one day on this and came up to this solution!
Note: If you are still getting bad-base64 error consider other Base64.decode flags like Base64.URL_SAFE and so on