简单的使用
在使用下面代码获取bitmap,即为压缩后的一个缩略图了,
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还是有点慢,暂时只做到此了。
本文介绍了一种优化Bitmap加载的方法,通过BitmapFactory.Options设置inJustDecodeBounds为true获取图片尺寸,再计算合适的inSampleSize值,从而减少内存占用并提高加载速度。
300

被折叠的 条评论
为什么被折叠?



