Drim
Drim

Reputation: 524

Decoding base64 String to Bitmap in Android

Code

public Bitmap StringToBitMap(String encodedString){          
   try{              
         byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);               
         Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
         return bitmap;
       }catch(Exception e){
           e.getMessage();
           return null;
       } 
}

this always return null even i gave it encoded64 (utf-8) string--->aGVsbG8=

Why this happening any one have idea..?? What i am doing Wrong can Any one Suggest me...

Upvotes: 0

Views: 2718

Answers (2)

samgak
samgak

Reputation: 24417

I think the problem is that you are trying to decode a base64 string to Bitmap, but actually you just want to decode it to a string. Here's the code to do that:

String decodeBase64String(String encodedString)
{
    byte[] data = Base64.decode(encodedString, Base64.DEFAULT);
    return new String(data, "UTF-8");
}

(assumes UTF-8 encoding)

If you call this function with your test string like this:

String result = decodeBase64String("aGVsbG8=");

then result will be "hello".

Here's how to convert text to a Bitmap:

Bitmap textToBitmap(String text)
{
     Paint paint = new Paint();
     paint.setColor(Color.WHITE);
     paint.setStrokeWidth(12);
     Rect bounds = new Rect();
     paint.getTextBounds(text, 0, text.length(), bounds);
     Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
     Canvas canvas = new Canvas(bitmap);
     canvas.drawText(text, 0, 0, paint);
     return bitmap;
}

So you can convert your base64 encoded text to a bitmap like this:

String result = decodeBase64String("aGVsbG8=");
Bitmap bitmap = textToBitmap(result);

Or you could just do this:

Bitmap bitmap = textToBitmap("hello");

Upvotes: 1

anupam sharma
anupam sharma

Reputation: 1705

you can revert your code using some other built in methods.

  String base="****Base64 string values of some image******”;
  byte[] imageAsBytes = Base64.decode(base.getBytes(), Base64.DEFAULT);
  ImageView image = (ImageView)this.findViewById(R.id.imageView1);
  image.setImageBitmap(
  BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)

Upvotes: 1

Related Questions