How to convert a Base64 string into a Bitmap image to show it in a ImageView?

后端 未结 6 2167
臣服心动
臣服心动 2020-11-22 10:23

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

H

6条回答
  •  情书的邮戳
    2020-11-22 10:53

    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

    data:image/jpg;base64

    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:

    Glide.with(CaptchaFragment.this).load(decodedBytes).crossFade().fitCenter().into(mCatpchaImageView);
    

    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

提交回复
热议问题