加载照片时Bitmap OutOfMemoryException

时间:2016-02-10 22:00:02

标签: java android bitmap out-of-memory

在我的应用程序中,用户可以启动相机意图并拍照并将其保存到自定义文件夹。然后,他们可以重新启动相机以拍摄另一张照片等。因此,最终用户可以拍摄多张照片。

我遇到的问题是,在我的图库中,当我尝试将所有图片加载到位图以放置在我的图片视图中时,我得到java.lang.OutOfMemoryError例外。我已经对内存管理有所了解,但我认为我已经弄明白了。这是我的代码到目前为止的样子:

File folder = new File(dir + "/");//contains anything from 1-20 pictures
File[] allPics = folder.listFiles();

private Bitmap[] thumbnails;
private String[] arrPath;

//load all the files into bitmaps to assign to my gridview adapter
for (int i = 0; i < allPics.length; i++) {
            thumbnails[i] = BitmapFactory.decodeFile(allPics[i].getAbsolutePath());//where the exception is thrown

            arrPath[i]= allPics[i].getAbsolutePath();
        }

堆栈跟踪:

pcemobileapp E/AndroidRuntime: FATAL EXCEPTION: main
 Process: pcemobileapp, PID: 7069
 java.lang.OutOfMemoryError
     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
     at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:719)
     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:695)
     at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:452)
     at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:491)
     at pcemobileapp.CustomGalleryActivity.onCreate(CustomGalleryActivity.java:65)
     at android.app.Activity.performCreate(Activity.java:5459)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2458)
     at android.app.ActivityThread.access$900(ActivityThread.java:172)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:146)
     at android.app.ActivityThread.main(ActivityThread.java:5598)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
     at dalvik.system.NativeStart.main(Native Method))

1 个答案:

答案 0 :(得分:2)

这里非常简单。你正在一次解码一堆照片。不要那样做。如果数量很高,即使是高端设备也没有足够的内存。相反,保存位图的位置,并仅在getView中膨胀位图。如果性能不够,可以使用LRU缓存并将最后N个位图存储在内存中。但你不能只是夸大大量的图像。