我们都知道在为imageview设置background或者src参数的时候,很容易导致内存溢出的问题,因为安卓系统在把图片资源设置给imageview的时候,安卓系统内部会利用bitmapfactory的一些函数进行处理,一些运行内存小的机型很容因为bitmapfactory所操作的内存太大而内存溢出,或者有时候系统中bitampfactory产生的bitmap变量在用完后没有及时清理掉,导致占用内存,内存溢出,下面提供给大家一个bitmap的压缩方法来解决这样的问题。
//此处是主程序调用的代码
BitmapFactory.Options option = new BitmapFactory.Options();
option.inJustDecodeBounds = true;
BitmapFactory.decodeFile(图片的uri,option);
option.inSampleSize = computerSampleSize(option,-1,65 * 65);
//此处的65*65是自己要设定的图片的尺寸
option.inJustDecodeBounds = false;
try{
Bitmap bitmap = BitmapFactory.decodeFile(图片的uri.option);
}catch(OutOfMemoryError err){
Log.d("oom","out of memory");
}
//此处为两个上述代码需要调用的两个方法
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
经此方法,可以根据图片的uri,自己做一个bitmap对象,然后把它设置到想要显示的imageview,就不会出现oom了。