android bitmap压缩图片

我们都知道在为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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子夜微凉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值