将图像加载到位图并获取OutOfMemoryError异常

时间:2016-06-09 10:11:36

标签: java android caching bitmap out-of-memory

我想加载很多像instagram这样的图像,但仍然得到OutOfMemory我的代码一次加载18个图像,并可以向下滚动以加载更多。 我还将图像缓存到磁盘并调整图像大小以适应缩略图,然后再加载到Bitmap

    private Bitmap loadBitmap(String id) throws IOException{
        String key = id.toLowerCase();

        // Check disk cache in background thread
        Bitmap image = cacher.get(key);

        if (image == null){
            // Not found in disk cache
            // Process as normal
            if(!isCancelled()){
                //download image to stream
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                DriveApiActivity.getService().files().get(id)
                        .executeMediaAndDownloadTo(stream);

                //decode image to byte array
                byte[] byteArray = stream.toByteArray();
                stream.close();

                //decode byte array to bitmap file
                image = decodeToBitmap(
                        byteArray,
                        CustomCardView.width,
                        CustomCardView.height);

                // Add final bitmap to caches
                cacher.put(key, image);
            }
        }
        return image;

    }

Logcat说异常来自cacher.get()方法

    public Bitmap get(String key) {
    synchronized (diskCacheLock) {
        // Wait while disk cache is started from background thread
        while (diskCacheStarting) {
            try {
                diskCacheLock.wait();
            } catch (InterruptedException e) {
                Toast.makeText(
                context,
                "getBitmapFromCache:" + e.getMessage(),
                4).show();
            }
        }
        if (diskLruCache != null) {
            Bitmap bitmap = null;
            DiskLruCache.Snapshot snapshot = null;
            try{
                snapshot = diskLruCache.get(key);
                if(snapshot == null){
                    return null;
                }
                final InputStream in = snapshot.getInputStream(0);
                if(in != null){
                    final BufferedInputStream buffIn =
                            new BufferedInputStream(in, Utils.IO_BUFFER_SIZE);
                    bitmap = BitmapFactory.decodeStream(buffIn);
                }
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(snapshot != null){
                    snapshot.close();
                }
            }

            if(BuildConfig.DEBUG){
                Log.d( "cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
            }

            return bitmap;
        }
    }
    return null;
}

此代码来自DiskLruCache谷歌提供的

1 个答案:

答案 0 :(得分:0)

你必须使用:

largeheap = true  

在android中。清单文件,从这一行你不能出现内存错误

它将解决您的问题