android将bitmap写入缓存,和从缓存中读取
时间: 2024-04-30 12:21:27 浏览: 245
从源代码分析Android Universal ImageLoader的缓存处理机制
将Bitmap写入缓存可以使用Android的LruCache类或DiskLruCache类。LruCache是一种内存缓存,而DiskLruCache是一种磁盘缓存。
以下是将Bitmap写入LruCache的示例代码:
```
// 初始化LruCache
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> memoryCache = new LruCache<String, Bitmap>(cacheSize);
// 写入Bitmap到LruCache
String key = "myBitmapKey";
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_bitmap);
memoryCache.put(key, bitmap);
```
以下是从LruCache中读取Bitmap的示例代码:
```
// 从LruCache中读取Bitmap
String key = "myBitmapKey";
Bitmap bitmap = memoryCache.get(key);
if (bitmap != null) {
// 使用Bitmap
} else {
// LruCache中没有该Bitmap
}
```
以下是将Bitmap写入DiskLruCache的示例代码:
```
// 初始化DiskLruCache
File cacheDir = getDiskCacheDir(this, "myCacheDir");
int appVersion = getAppVersion(this);
int valueCount = 1;
long maxSize = 10 * 1024 * 1024; // 10MB
DiskLruCache diskCache = DiskLruCache.open(cacheDir, appVersion, valueCount, maxSize);
// 写入Bitmap到DiskLruCache
String key = "myBitmapKey";
DiskLruCache.Editor editor = diskCache.edit(key);
if (editor != null) {
OutputStream outputStream = editor.newOutputStream(0);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_bitmap);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
editor.commit();
}
// 关闭DiskLruCache
diskCache.close();
```
以下是从DiskLruCache中读取Bitmap的示例代码:
```
// 从DiskLruCache中读取Bitmap
String key = "myBitmapKey";
DiskLruCache.Snapshot snapshot = diskCache.get(key);
if (snapshot != null) {
InputStream inputStream = snapshot.getInputStream(0);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 使用Bitmap
}
```
阅读全文