您的位置:首页 > 其它

简单记录,使用Bitmap压缩时遇到的耗时过长的问题。

2013-05-16 14:29 169 查看
简单的使用
Bitmap bitmap = BitmapFactory.decodeFile(path);

如果图片过大,例如2.5M这个步骤将会耗时大概800ms,而且还需要及时的进行内存回收以避免OOM。

经过咨询同事,改为通过
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
来获取bitmap的高和宽,然后在进行计算获取一个比较合适的解析度进行解析,
o.inSampleSize = computeSampleSize(o, -1, 128 * 128);
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;
}
}


在使用下面代码获取bitmap,即为压缩后的一个缩略图了,
o.inJustDecodeBounds = false;
Bitmap newBitmap = BitmapFactory.decodeStream(
new FileInputStream(new File(m)), null, o);


测试此过程大概耗时100+ms还是有点慢,暂时只做到此了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: