Android BitmapFactory decodeResource Out of Memory Exception

问题描述 投票:0回答:1

我是Android的新手,开发了一个应用程序,可以将大图像从可绘制文件夹保存到手机存储。这些文件的分辨率为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"不是一个好习惯。

是否有任何有效的方法来保存可绘制文件夹中的大图像而没有例外?

先感谢您。

android android-image android-bitmap android-file bitmapfactory
1个回答
3
投票

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

您可以使用此复制原始资源文件,例如:

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/中。

© www.soinside.com 2019 - 2024. All rights reserved.