1
BitmapFactory.decodeFile(imageFile);
用BitmapFactory解码一张图片时,有时会遇到该错误。这往往是由于图片过大造成的。要想正常使用,则需要分配更少的内存空间来存储。
BitmapFactory.Options.inSampleSize
设置恰当的inSampleSize可以使BitmapFactory分配更少的空间以消除该错误。inSampleSize的具体含义请参考SDK文档。例如:
1
BitmapFactory.Options opts = new BitmapFactory.Options();
2
opts.inSampleSize = 4;
3
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);
如何设置恰当的inSampleSize
设置恰当的inSampleSize是解决该问题的关键之一。BitmapFactory.Options提供了另一个成员inJustDecodeBounds。
1
BitmapFactory.Options opts = new BitmapFactory.Options();
2
opts.inJustDecodeBounds = true;
3
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);
设置inJustDecodeBounds为true后,decodeFile并不分配空间,但可计算出原始图片的长度和宽度,即opts.width和opts.height。有了这两个参数,再通过一定的算法,即可得到一个恰当的inSampleSize。
查看Android源码,Android提供了一种动态计算的方法。
01
public static int computeSampleSize(BitmapFactory.Options options,
02
int minSideLength, int maxNumOfPixels) {
03
int initialSize = computeInitialSampleSize(options, minSideLength,
04
maxNumOfPixels);
05
06
int roundedSize;
07
if (initialSize <=
{
08
roundedSize = 1;
09
while (roundedSize < initialSize) {
10
roundedSize <<= 1;
11
}
12
} else {
13
roundedSize = (initialSize + 7) / 8 * 8;
14
}
15
16
return roundedSize;
17
}
18
19
private static int computeInitialSampleSize(BitmapFactory.Options options,
20
int minSideLength, int maxNumOfPixels) {
21
double w = options.outWidth;
22
double h = options.outHeight;
23
24
int lowerBound = (maxNumOfPixels == -1) ? 1 :
25
(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
26
int upperBound = (minSideLength == -1) ? 128 :
27
(int) Math.min(Math.floor(w / minSideLength),
28
Math.floor(h / minSideLength));
29
30
if (upperBound < lowerBound) {
31
// return the larger one when there is no overlapping zone.
32
return lowerBound;
33
}
34
35
if ((maxNumOfPixels == -1) &&
36
(minSideLength == -1)) {
37
return 1;
38
} else if (minSideLength == -1) {
39
return lowerBound;
40
} else {
41
return upperBound;
42
}
43
}
使用该算法,就可动态计算出图片的inSampleSize。
01
BitmapFactory.Options opts = new BitmapFactory.Options();
02
opts.inJustDecodeBounds = true;
03
BitmapFactory.decodeFile(imageFile, opts);
04
05
opts.inSampleSize = computeSampleSize(opts, -1, 128*128);
06
opts.inJustDecodeBounds = false;
07
try {
08
Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);
09
imageView.setImageBitmap(bmp);
10
} catch (OutOfMemoryError err) {
11
}
另外,可以通过Bitmap.recycle()方法来释放位图所占的空间,当然前提是位图没有被使用。