BitmapFactory. Options. inSampleSize usage, options. insamplesize
BitmapFactory. decodeFile (imageFile );
This error is sometimes encountered when BitmapFactory is used to decode an image. This is often caused by an excessively large image. For normal use, you need to allocate less memory for storage.
BitmapFactory. Options. inSampleSizeSetting the appropriate inSampleSize allows BitmapFactory to allocate less space to eliminate this error. For more information about inSampleSize, see the SDK documentation. For example:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);
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.
Public StaticBitmap createImageThumbnail (String filePath ){
Bitmap bitmap =Null;
BitmapFactory. Options opts =NewBitmapFactory. Options ();
Opts. inJustDecodeBounds =True;
BitmapFactory. decodeFile (filePath, opts );
Opts. inSampleSize = computeSampleSize (opts,-1,128*128 );
Opts. inJustDecodeBounds =False;
Try{
Bitmap = BitmapFactory. decodeFile (filePath, opts );
}Catch(Exception e ){
// TODO: handle exception
}
ReturnBitmap;
}
Public Static IntComputeSampleSize (BitmapFactory. Options options,IntMinSideLength,IntMaxNumOfPixels ){
IntInitialSize = computeInitialSampleSize (options, minSideLength, maxNumOfPixels );
IntRoundedSize;
If(InitialSize <= 8 ){
RoundedSize = 1;
While(RoundedSize <initialSize ){
RoundedSize <= 1;
}
}Else{
RoundedSize = (initialSize + 7)/8*8;
}
ReturnRoundedSize;
}
Private Static IntComputeInitialSampleSize (BitmapFactory. Options options,IntMinSideLength,IntMaxNumOfPixels ){
DoubleW = options. outWidth;
DoubleH = options. outHeight;
IntLowerBound = (maxNumOfPixels =-1 )? 1 :(Int) Math. ceil (Math. sqrt (w * h/maxNumOfPixels ));
IntUpperBound = (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.
ReturnLowerBound;
}
If(MaxNumOfPixels =-1) & (minSideLength =-1 )){
Return1;
}Else If(MinSideLength =-1 ){
ReturnLowerBound;
}Else{
ReturnUpperBound;
}
}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.