java - 将编码的 base64 图像转换为 Android 中的文件对象

标签 java android image blob android-image

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

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

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

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

最佳答案

您需要将 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;
}

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

关于java - 将编码的 base64 图像转换为 Android 中的文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005815/

相关文章:

android - 你如何用opengl es显示fps(android)

Android SDK Nexus S 原生相机问题

android - 设置动画后图像位置

java - 跨多个线程访问字符串

java - 正则表达式删除与字母相邻的标点符号

java - 如何在 Java TicTacToe 程序中将空字符转换为空白字符?

java - NPE 在尝试在 java 中创建多个记录器时使用静态 ThreadLocal 记录器

android - 我一直在 Android 中获取不准确的位置

java - 将图像复制到新目录并重命名 - Java

python - 区分 PIL 和 CV2 图像