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

10

238

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);
Camelopardus answered 29/1, 2011 at 13:28 Comment(0)
C
430

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); 
Cello answered 29/1, 2011 at 14:7 Comment(3)
make sure you are not passing the "data:image/jpg;base64" and pass only the image bytes.. Don't forget to change the string to bytes.. photoData = photoData.substring(photoData.indexOf(",") + 1); byte[] decodedString = Base64.decode(photoData.getBytes(), Base64.DEFAULT); Hope it helps for someone.Italianate
as answered already If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULTPena
To remove the data:image... for both png and jpeg try this: String cleanImage = base64Image.replace("data:image/png;base64,", "").replace("data:image/jpeg;base64,","");Ferrel
L
83

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

Look answered 4/3, 2016 at 15:13 Comment(1)
I got base64 from json response, used Base.64.URL_SAFE got bad-base64 error, Checked this thread and solved, Thumbs up man..Fellini
D
18

This is a very old thread but thought to share this answer as it took lot of my development time to manage NULL return of BitmapFactory.decodeByteArray() as @Anirudh has faced.

If the encodedImage string is a JSON response, simply use Base64.URL_SAFE instead of Base64.DEAULT

byte[] decodedString = Base64.decode(encodedImage, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Dissatisfactory answered 26/11, 2014 at 4:59 Comment(4)
i am getting a bad-base64 (IllegalArgumentException) error when using Base64.URL_SAFE. I verified the base64 string using an HTML img tag. I am seeing the image on HTML page.Tjaden
Hi @mudit, did you figure out how to fix the bad-base64 exception? If so do you mind to share? I am having the same issue. Have been for two days now and running out of ideas.Introspection
@ito make sure you are not passing the "data:image/jpg;base64" and pass only the image bytes.. Don't forget to change the string to bytes.. photoData = photoData.substring(photoData.indexOf(",") + 1); byte[] decodedString = Base64.decode(photoData.getBytes(), Base64.DEFAULT);Italianate
I too struggled a lot for this one word "Base64.URL_SAFE".....I was fetching as json obj ...Thanks a tonPena
K
15

To check online you can use

http://codebeautify.org/base64-to-image-converter

You can convert string to image like this way

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView image =(ImageView)findViewById(R.id.image);

        //encode image to base64 string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        //decode base64 string to image
        imageBytes = Base64.decode(imageString, Base64.DEFAULT);
        Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        image.setImageBitmap(decodedImage);
    }
}

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

Kalevala answered 17/2, 2017 at 10:8 Comment(1)
Found the website very useful for figuring out if there was an issue with my code or with the image data. Thanks for sharing!Augustin
G
8

This is a great sample:

String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);

Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af

This is the only code that worked for me in the past.

Guile answered 14/8, 2020 at 16:29 Comment(1)
yeah i definitely couldn't get this working without splitting after the comma. i think this should be the accepted answer, thank you!!Fotheringhay
U
5

I've found this easy solution

To convert from bitmap to Base64 use this method.

private String convertBitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

To convert from Base64 to bitmap OR revert.

private Bitmap convertBase64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}
Unstudied answered 18/12, 2019 at 12:56 Comment(0)
M
2

In Kotlin you can use extension function as bellow:

fun String.base64ToByteCode() = Base64.decode(this.substring(this.indexOf(",")  + 1), Base64.DEFAULT)

and call it as bellow:

yourBase64String.base64ToByteCode()
Mortgage answered 16/7, 2021 at 8:28 Comment(1)
you can replace this.substring(this.indexOf(",") + 1) with substringAfter(",")Beverly
L
1

This solution is working fine for me. if you receive null please let me know.

private void bytesToImage(ImageView imageView, String base64String) {
        if (!base64String.isEmpty()) {
            byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
            Bitmap decodedByte = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    
           Glide.with(this).load(decodedByte).into(imageView);
    
            
        }
Lanceted answered 28/7, 2022 at 10:10 Comment(1)
if you decide to use Glide you can load the base64 string directly into the imageView. there is no need to decode it yourself, just pass your base64 string to glide and it'll do the reset.Catechetical
T
0

I have tried all the solutions and this one worked for me

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage
Tontine answered 2/1, 2021 at 4:5 Comment(0)
A
0

In Kotlin, you can create an extension function on ImageView like below:

fun ImageView.loadFromBase64(encodedImageString: String) {
    try {
         val base64Image = encodedImageString.split(",")[1]
         val decodedString = Base64.decode(base64Image, Base64.DEFAULT)
         val bitmap = 
         BitmapFactory.decodeByteArray(decodedString,0,decodedString.size)
         setImageBitmap(bitmap)
    } catch (e: Exception) {
         Timber.d("Error loading image from base64: ${e.message}")
    }
}

At the point of usage, you can easily do:

imageView.loadFromBase64(encodedImageString)
Altogether answered 21/3, 2023 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.