我正在尝试使用 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/