【问题标题】:Convert encoded base64 image to File object in Android在Android中将编码的base64图像转换为文件对象
【发布时间】:2015-07-12 09:41:04
【问题描述】:

我正在尝试使用 AndroidImageSlider 库并使用我下载为 base64 字符串的图像填充它。

该库仅接受 URL、R.drawable 值和 File 对象作为参数。

我正在尝试将图像字符串转换为 File 对象,以便传递给库函数。到目前为止,我已经能够从 base_64 解码并转换为 byte[]。

String imageData;
byte[] imgBytesData = android.util.Base64.decode(imageData, android.util.Base64.DEFAULT);

【问题讨论】:

  • 我认为最好使用FileOutputStream 创建文件,然后从服务器上的静态 URL 提供它。假设图像数据已经是你想要的格式,只需要将数据写入文件即可。请参阅此 SO 线程:stackoverflow.com/questions/20879639/…
  • 但是如果我要创建一个FileOutputStream,我应该如何访问一个文件对象?该库特别想要 File 参数,FileOutputStream 是否还有更多内容?
  • 将图像写入文件后,只需从 restful url 提供服务。无论如何,你似乎把它修好了!

标签: java android image blob android-image


【解决方案1】:

您需要将File 对象保存到磁盘上才能正常工作。此方法会将imageData 字符串保存到磁盘并返回关联的File 对象。

public static File saveImage(final Context context, final String imageData) {
    final byte[] imgBytesData = android.util.Base64.decode(imageData,
            android.util.Base64.DEFAULT);

    final File file = File.createTempFile("image", null, context.getCacheDir());
    final FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }

    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
            fileOutputStream);
    try {
        bufferedOutputStream.write(imgBytesData);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

它会在您的应用程序“缓存”目录中创建一个临时文件。但是,一旦不再需要该文件,您仍有责任将其删除。

【讨论】:

  • 非常感谢兄弟!,您能告诉我如何从应用程序目录中删除这些 .temp 文件吗?提前致谢
猜你喜欢
  • 2017-09-24
  • 2020-07-26
  • 2013-03-18
  • 2011-04-27
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 2019-12-10
相关资源
最近更新 更多