user291977
user291977

Reputation: 247

Converting base64 String to image in Android

Is there any way that I can convert a base64 String to image in Android? I am receiving this base64 String in a xml from the server connected through socket.

Upvotes: 6

Views: 12540

Answers (4)

ThomasW
ThomasW

Reputation: 17307

There are now Base64 utilities in Android, but they only became available with Android OS 2.2.

Upvotes: 1

valerybodak
valerybodak

Reputation: 4413

If you want to convert base64 string to the image file (for example .png etc.) and save it to some folder you can use this code:

byte[] btDataFile = Base64.decode(base64Image, Base64.DEFAULT);
String fileName = YOUR_FILE_NAME + ".png";
try {

  File folder = new File(context.getExternalFilesDir("") + /PathToFile);
  if(!folder.exists()){
    folder.mkdirs();
  }

  File myFile = new File(folder.getAbsolutePath(), fileName);
  myFile.createNewFile();

  FileOutputStream osf = new FileOutputStream(myFile);
  osf.write(btDataFile);
  osf.flush();
  osf.close();
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} 

And make sure you have given the following required permission in your manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Upvotes: 0

mukama
mukama

Reputation: 979

After failing to get any solutions (even on Stackoverflow), I built a plugin that converts Base64 PNG Strings to files which I shared here. Hope that helps.

Upvotes: 0

aioobe
aioobe

Reputation: 420921

Have a look at http://www.source-code.biz/base64coder/java/ or any other example that converts base64 strings to byte-arrays, and then use the ImageIcon(byte[] imageData) constructor.

Upvotes: 1

Related Questions