bitmap
Bitmap 的内存消耗主要取决于 Bitmap 的宽度、高度和配置(即像素格式)。跟 ImageView 的宽高没有关系
# bitmap 优化
# 1. 使用适当的 Bitmap 配置
选择适合的 Bitmap.Config,例如 Bitmap.Config.RGB_565,可以减少内存使用量。这种配置使用 2 字节来存储每个像素,而 Bitmap.Config.ARGB_8888 使用 4 字节
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);
1
2
3
2
3
# 2. 缩放 Bitmap
如果你需要展示的 Bitmap 尺寸小于原图的尺寸,可以先缩放 Bitmap 以减少内存使用
public static Bitmap getScaledBitmap(String path, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
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 halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 3. 使用 BitmapFactory.Options 进行解码
通过设置 BitmapFactory.Options 来控制解码过程中的内存使用
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true; // 允许系统在内存不足时回收该Bitmap的内存
options.inInputShareable = true; // 与inPurgeable配合使用
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);
1
2
3
4
2
3
4
# 4. 回收 Bitmap 内存
在不再需要 Bitmap 时,及时调用 bitmap.recycle()方法释放内存
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
1
2
3
4
2
3
4
# 5. 使用内存缓存
使用内存缓存(如 LruCache)来缓存 Bitmap,从而避免频繁加载和解码
private LruCache<String, Bitmap> memoryCache;
public void initCache() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
memoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
memoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return memoryCache.get(key);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 6. 使用硬件加速
在 Android 8.0 (API level 26)及更高版本中,可以使用硬件位图(Hardware Bitmaps),这些位图存储在 GPU 内存中,可以减少应用的内存使用
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image, options);
bitmap.setConfig(Bitmap.Config.HARDWARE);
}
1
2
3
4
2
3
4
# link
上次更新: 2024/12/01, 17:09:08