java.lang.OutOfMemoryError: bitmap size exceeds VM budget

来源:互联网 发布:淘宝优惠款 编辑:程序博客网 时间:2024/05/18 22:51

这个问题没有让程序员头疼,年尾自己查了些资料找到了问题所在,不多说了,直接上代码(友情提示,此方案主要针对用BitmapFactory解码一张图片时)

http://www.eoeandroid.com/forum.php?mod=viewthread&tid=255039

/*** @author i-marsw*查看Android源码,Android提供了一种动态计算的方法。*用BitmapFactory解码一张图片时,有时会遇到该错误:java.lang.OutOfMemoryError: bitmap size exceeds VM budget*这往往是由于图片过大造成的,要想正常使用,则需要分配更少的内存空间来存储。*/public class BitmapSampleSize { 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 the larger one when there is no overlapping zone.return lowerBound;} if ((maxNumOfPixels == -1) &&(minSideLength == -1)) {return 1;} else if (minSideLength == -1) {return lowerBound;} else {return upperBound;}} }


下面是我做测试是调用上面类的部分代码:

BitmapFactory.Options opts = new BitmapFactory.Options();opts.inJustDecodeBounds = true;// 设置inJustDecodeBounds为true后,decodeFile并不分配空间// 但可计算出原始图片的长度和宽度,即opts.width和opts.height,// 有了这两个参数,再通过一定的算法,即可得到一个恰当的inSampleSizeBitmapFactory.decodeFile(imagePath, opts); // 计算出图片使用的inSampleSizeopts.inSampleSize = BitmapSampleSize.computeSampleSize(opts, -1, opts.outWidth*opts.outHeight); // 这里一定要设置成false,因为上面设置成trueopts.inJustDecodeBounds = false;try {result = BitmapFactory.decodeFile(imagePath,opts);} catch (OutOfMemoryError err) {// 在此处还可以在不牺牲图片失贞的情况下开辟一个临时空间,然后把大图片资源载入里面}


?
原创粉丝点击