Hi stackoverflow team i have a problem in converting base64 string to bitmap in android. I am using the camera to fetch the image and i am convert the image to base64 string to post to the server. I want to show that image in the imageview so how can i show the image in the ImageView after fetching the image from the camera. please help me to solve the problem.
Asked
Active
Viewed 3.3k times
11
-
3Just for better understanding: Why would you want to encode the image in base64 first, then send decode it to display it again into the ImageView? Wouldn't it be easier to fetch it first, display it in the ImageView and then encoding it into base64 to send it to the server? ^^ – Tseng Sep 27 '10 at 18:56
3 Answers
21
Assuming that your image data is in a String called myImageData, the following should do the trick:
byte[] imageAsBytes = Base64.decode(myImageData.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
For Base64 decoding, you can use http://iharder.sourceforge.net/current/java/base64/ as Android doesn't contain Base64-support prior to 2.2.
Note, I didn't actually run this code, so you'll have to doublecheck for errors.

TuomasR
- 2,296
- 18
- 28
-
1In my case: `byte[] imageBitmap = Base64.decode(mEncodedImageData, Base64.DEFAULT); ` – Shajeel Afzal Apr 04 '15 at 09:12
8
EDIT: Accepted post has now been updated to copy my answer below, either are correct
The accepted answer is not correct at least in JellyBean, KitKat or Lollipop. You should use the following which works for JPEG, PNG or GIF images.
byte[] imageAsBytes = Base64.decode(myImageData.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);

Apqu
- 4,880
- 8
- 42
- 68
-
Tur - is this not the same code as TuomasR's (which is the accepted answer)? – AshesToAshes Aug 09 '15 at 08:13
-
2@AshesToAshes It is now they have updated their answer to copy mine (http://stackoverflow.com/posts/3801881/revisions) – Apqu Aug 13 '15 at 12:45
3
Write down the Simple method pass the Base64 String and it will return the Bitmap object
Bitmap Base64ToBitmap(String myImageData)
{
byte[] imageAsBytes = Base64.decode(myImageData.getBytes(),Base64.DEFAULT);
return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}

Blazemonger
- 90,923
- 26
- 142
- 180
-
This worked for me. can you explain this conversion theoratically?? – Kartiikeya Nov 01 '16 at 09:47