Android BitmapFactory解码资源内存不足异常



我是安卓系统的新手,正在开发一款应用程序,可以将大型图像从可绘制文件夹保存到手机存储中。这些文件的分辨率为2560x2560,我想保存这些文件而不丢失图像质量。

我使用以下方法来保存图像,它会给我内存不足异常。我已经看到了很多关于如何高效加载大位图的答案。但是我真的找不到这个问题的答案。

在我的代码中,我使用

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageId);
File file = new File(root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg");
file.createNewFile();
FileOutputStream oStream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, oStream);
oStream.close();
bitmap.recycle();

我的代码有什么问题吗?这对较小的图像毫无例外。

如果我使用android:largeHeap="true",这不会引发任何异常。但我知道使用android:largeHeap="true"不是一个好的做法。

有没有什么有效的方法可以毫无例外地从可绘制的文件夹中保存大图像?

提前谢谢。

如果只想复制图像文件,首先不应该将其解码为位图。

您可以复制一个原始资源文件,例如:

InputStream in = getResources().openRawResource(imageId);
String path = root.getAbsolutePath() + "/Pictures/" + getResources().getString(R.string.app_name) + "/" + timeStamp + ".jpg";
FileOutputStream out = new FileOutputStream(path);
try {
    byte[] b = new byte[4096];
    int len = 0;
    while ((len = in.read(b)) > 0) {
        out.write(b, 0, len);
    }
}
finally {
    in.close();
    out.close();
}

请注意,您必须将图像存储在res/raw/目录中,而不是res/drawable/目录中。

最新更新