LruCache实现图片缓存

1 图片的加载通常会导致OOM异常:

 处理:

 1) 计算图片可能得压缩比例 (inSampleSize压缩比例)

  2)将图片压缩 

  3 )计算应用程序可能得到的最大内存,实例化LruCache,并赋予适当的缓存空间

        原理:把最近使用的对象用强引用存储在 LinkedHashMap 中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除

 计算压缩比例:

1 计算加载图片的实际尺寸(inJustDecodebounds=true程序会解析图片的实际尺寸,因为不反会Bitmap所以不占用内存,false则会返回bitmap对象)

  

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,  
        int reqWidth, int reqHeight) {  
    // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小  
    final BitmapFactory.Options options = new BitmapFactory.Options();  
    options.inJustDecodeBounds = true;  
    BitmapFactory.decodeResource(res, resId, options);  
    // 调用上面定义的方法计算inSampleSize值  
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
    // 使用获取到的inSampleSize值再次解析图片  
    options.inJustDecodeBounds = false;  
    return BitmapFactory.decodeResource(res, resId, options);  
}  

 2 实际尺寸和所需要的尺寸来计算压缩比例

public static int calculateInSampleSize(BitmapFactory.Options options,  
        int reqWidth, int reqHeight) {  
    // 源图片的高度和宽度  
    final int height = options.outHeight;  
    final int width = options.outWidth;  
    int inSampleSize = 1;  
    if (height > reqHeight || width > reqWidth) {  
        // 计算出实际宽高和目标宽高的比率  
        final int heightRatio = Math.round((float) height / (float) reqHeight);  
        final int widthRatio = Math.round((float) width / (float) reqWidth);  
        // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高  
        // 一定都会大于等于目标的宽和高。  
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;  
    }  
    return inSampleSize;  
}  

 3 实例化缓存

  

		// 获取应用程序最大可用内存
		int maxMemory = (int) Runtime.getRuntime().maxMemory();
		int cacheSize = maxMemory / 5;
		System.out.println("总缓存大小:;"+cacheSize );
		// 设置图片缓存大小为程序最大可用内存的1/8
		 LruCache<String, Bitmap>= new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				return bitmap.getByteCount();
			}
		};


  

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
    if (getBitmapFromMemCache(key) == null) {  
        mMemoryCache.put(key, bitmap);  
    }  
}  
  
public Bitmap getBitmapFromMemCache(String key) {  
    return mMemoryCache.get(key);  
}  

  

  附件中是Gallary加载网路图片的例子

  

参考:

http://blog.csdn.net/luohai859/article/details/38660467

http://blog.csdn.net/luohai859/article/details/38660257

猜你喜欢

转载自username2.iteye.com/blog/2229337