在Android中将base64字符串转换为图片

6
有没有办法在Android中将base64字符串转换为图像?我从通过套接字连接的服务器中以xml格式收到这个base64字符串。

1
可能是重复的问题:如何将图像转换为Base64字符串? - Bo Persson
4个回答

1

1

现在 Android 中有 Base64 实用程序,但它们只能在 Android OS 2.2 及以上版本中使用。


0
如果您想将 base64 字符串转换为图像文件(例如 .png 等),并将其保存到某个文件夹中,可以使用以下代码:
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();
} 

同时确保您在清单文件中已经授予了以下所需的权限:

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

0

在 Stackoverflow 上找不到任何解决方案后,我构建了一个插件,将 Base64 PNG 字符串转换为文件,并在这里分享。 希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接