VLC项目学习之图片缓存

Vlc在显示歌曲列表时会加载该歌曲的封面,对于图片采取了相应的缓存机制:

1.  内存缓存

2.  文件缓存


内存缓存:

采用的是LruCache,对于使用LruCache需要注意的是分配多少内存给它去存储图片。Vlc中使用了1/5的可用内存存储图片。

        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        final int memClass = ((ActivityManager) context.getSystemService(
                Context.ACTIVITY_SERVICE)).getMemoryClass();

        // Use 1/5th of the available memory for this 	 cache.
        final int cacheSize = 1024 * 1024 * memClass / 5;

        Log.d(TAG, "LRUCache size sets to " + cacheSize);

        mMemCache = new LruCache<String, Bitmap>(cacheSize) {

            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }

        };
对于图片缓存,注意点是计算图片的size,Vlc中采用的是

protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
查询 stackoverflow后,发现

protected int sizeOf(Bitmap data) {
       int size = 0;
       if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
	     size = value.getRowBytes() * value.getHeight();
	} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
	     size = value.getByteCount();
	} else {
	     size = value.getAllocationByteCount();
	}
      return size;
 }
不清楚为什么老版本用 value.getRowBytes() * value.getHeight()计算图片的size。 

文件缓存:

private static void writeBitmap(Bitmap bitmap, String path)
			throws IOException {
		OutputStream out = null;
		try {
			File file = new File(path);
			if (file.exists() && file.length() > 0)
				return;
			out = new BufferedOutputStream(new FileOutputStream(file), 4096);
			if (bitmap != null)
				bitmap.compress(CompressFormat.JPEG, 90, out);
		} catch (Exception e) {
			Log.e(TAG, "writeBitmap failed : " + e.getMessage());
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值