Thursday, October 20, 2011

Bitmap out of memory

Image size Out of Memory you can use this code:
(android BitmapFactory.decodeStream out of memory error)

BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(files[i].getAbsolutePath());
BitmapFactory.decodeStream(fis, null, o);
fis.close();
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options op = new BitmapFactory.Options();
op.inSampleSize = scale;
fis = new FileInputStream(files[i].getAbsolutePath());
bitmap = BitmapFactory.decodeStream(fis, null, op);
fis.close();
===============================
you can also use this :
bitmap.recycle();
after using the bitmap every time use this method so that it will free the memory and now memory will be available for next bitmap.
Example:
Bitmap bm = BitmapFactory.decodeStream(instream);

Bitmap useThisBitmap = Bitmap.createScaledBitmap(bm,bm.getWidth(),bm.getHeight(), true);
bm.recycle();
BitmapDrawable bt= new BitmapDrawable(useThisBitmap);


I am sure it will solve the out of memory problem.



8 comments:

  1. Thanks for the post. It solved my problem with my decodeStream outOfMemoryError

    ReplyDelete
    Replies
    1. can youn tell me how did u use?
      My problem is:

      04-16 17:18:38.243 2032 2032 E AndroidRuntime: FATAL EXCEPTION: main
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: java.lang.OutOfMemoryError
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:577)
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:445)
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:773)
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.content.res.Resources.loadDrawable(Resources.java:1937)
      04-16 17:18:38.243 2032 2032 E AndroidRuntime: at android.content.res.TypedArray.getDrawable(TypedArray.java:601)

      Delete
  2. How to decide value for REQUIRED_SIZE

    ReplyDelete
  3. Actually REQUIRED_SIZE is depend upon the size of image which we need, if we want to show thumbnail then we can take 50-150, i mean its all on acquirement what we want and where we using...

    ReplyDelete
  4. I don't want to scale down image(without loosing image quality loading file of size 500mb. can u help me

    ReplyDelete
  5. Thnx a lot dude, your code works perfect. I didn't even get Single OutOfMemory Crash issue while using ur Code.

    ReplyDelete