Compress images by sample rate
When using BitmapFactory's parsing methods (decodeResource, decodeFile...) to create a Bitmap, you can pass in a BitmapFactory.Option parameter, and set the inJustDecodeBounds property of this parameter to true to return only the image's length, width and MIME type without To really parse the image, we can compress the image first according to the situation.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.img, options);
After getting the information of the picture, we can calculate a value according to the size of the original picture and the size of the picture we need, set the inSampleSize of BitmapFactory.Options, and compress the picture according to the sampling rate through inSampleSize.
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// 计算出实际宽高和目标宽高的比率
int heightRatio = Math.round((float) height / (float) reqHeight);
int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值
// 这样可以保证最终图片的宽和高一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
options.inSampleSize = inSampleSize;
Finally, set inJustDecodeBounds to false and re-parse the image to get the compressed Bitmap
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.img, options);
Cache images with LruCache
First build the LruCache object
// 获取到可用内存的最大值
// 单位 KB
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// 使用最大可用内存值的1/8作为缓存的大小
int cacheSize = maxMemory / 8;
// 创建 LruCache 对象
lruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// 重写此方法来计算并返回每张图片的大小
// 单位需与传入的 cacheSize 一致,即 KB
return bitmap.getByteCount() / 1024;
}
};
Add pictures to LruCache, first determine whether it has been cached, if there is no cache, if not, add it to LruCache
public void addBitmapToLruCache(String key, Bitmap bitmap) {
if (getBitmapFromLruCache(key) == null) {
lruCache.put(key, bitmap);
}
}
Get cached images from LruCache
public Bitmap getBitmapFromLruCache(String key) {
return lruCache.get(key);
}