BitmapFactory类提供了四类方法:decodeResource、decodeFile、decodeByteArray、decodeStream,分别用于支持资源、文件、字节数组、输入流加载出一个Bitmap对象,其中decodeFile和decodeResource又间接调用了decodeStream方法,这四类方法是在Android的底层实现的。对应着BitmapFactory类的几个native 方法。
步骤
- 将BitmapFactory.Options()的inJustDecodeBounds参数设置为true,并加载图片。
- 从BitmapFactory.Options()中取出图片的原始宽高信息,它们对于outWidth和outHeight参数。
- 根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
- 将BitmapFactory.Options()的inJustDecodeBounds参数设置为false,然后重新加载图片。
/**
* 通过采样率压缩
* 获取采样率
* 1.将BitmapFactory.Options()的inJustDecodeBounds参数设置为true,并加载图片。
* 2.从BitmapFactory.Options()中取出图片的原始宽高信息,它们对于outWidth和outHeight参数。
* 3.根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
* 4.将BitmapFactory.Options()的inJustDecodeBounds参数设置为false,然后重新加载图片。
*
* @param resources
* @param resId
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap decodeSampleBitmapFromResource(Resources resources, int resId, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(resources, resId, options);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
调用 比如 ImageView 所期望的图片大小为100*100像素。
mainBinding.ivFactory.setImageBitmap( BitmapUtils.decodeSampleBitmapFromResource(getResources(), R.id.iv_factory, 100, 100));
除了decodeResource 方法,其他三个方法(decodeFile、decodeByteArray、decodeStream)也支持采样率加载,处理方式类似。
总结 Android性能优化需要考虑的方面
App启动流程
Android之启动优化
Android之图片压缩几种方式
Android 内存泄漏
Android 之 Handler
Java引用类型(强引用,软引用,弱引用,虚引用)
Java List、Set、Map区别
Java 之 String、StringBuffer与StringBuilder 区别
JVM之垃圾回收机制