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

来源:互联网 发布:idown mac 编辑:程序博客网 时间:2024/05/16 09:36
简单的使用
 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还是有点慢,暂时只做到此了。


原创粉丝点击