开发者

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 fr开发者_开发知识库om the server connected through socket.


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.


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


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.


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" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜