When the image size is too large or the number of images is too large, BitmapFactory decoding will produce java. lang. outOfMemoryError: bitmap size exceeds VM budget. To use it properly, you need to allocate less memory. The specific solution is to modify the sample value BitmapFactory. options. inSampleSize, for example, www.2cto.com
BitmapFactory. Options opts = new BitmapFactory. Options ();
Opts. inSampleSize = 4;
Bitmap bitmap = BitmapFactory. decodeFile (imageFile, opts); how to set the appropriate inSampleSize
Setting the appropriate inSampleSize is one of the keys to solve this problem. BitmapFactory. Options provides another member, inJustDecodeBounds.
BitmapFactory. Options opts = new BitmapFactory. Options ();
Opts. inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory. decodeFile (imageFile, opts );
After inJustDecodeBounds is set to true, decodeFile does not allocate space, but the length and width of the original image can be calculated, that is, opts. width and opts. height. With these two parameters, you can use a certain algorithm to obtain an appropriate inSampleSize.
Android provides a dynamic computing method to view the Android source code.
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;
}
}
This algorithm can be used to dynamically calculate the inSampleSize of an image.
BitmapFactory. Options opts = new BitmapFactory. Options ();
Opts. inJustDecodeBounds = true;
BitmapFactory. decodeFile (imageFile, opts );
Opts. inSampleSize = computeSampleSize (opts,-1,128*128 );
Opts. inJustDecodeBounds = false;
Try {
Bitmap bmp = BitmapFactory. decodeFile (imageFile, opts );
ImageView. setImageBitmap (bmp );
} Catch (OutOfMemoryError err ){
}
In addition, the Bitmap. recycle () method can be used to release the space occupied by the Bitmap, provided that the Bitmap is not used.
Author: LuoXianXion