Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemoryError in BitmapFactory.decodeFile()

When I pick image from gallery if image size bigger than 3 Mb android the OutOfMemoryError.

 BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, options);

This text from logs. Please help me, becouse "deadline")

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.OutOfMemoryError
        at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
        at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:623)
        at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:378)
        at com.DriverNotes.AndroidMobileClientTest.ProfileActivity.onActivityResult(ProfileActivity.java:104)
        at android.app.Activity.dispatchActivityResult(Activity.java:5456)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3402)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3449)
        at android.app.ActivityThread.access$1200(ActivityThread.java:150)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
like image 579
Artem Avatar asked Oct 20 '14 12:10

Artem


2 Answers

OutofMemory occurs when your app exceeds memory allocated in heap. The bitmap is too large to fit in memory ie heap. In such a case you run out of memory. You need to scale down the bitmap and then use the same.

For that check this link

try this code may help you,

 public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
 try {
     //Decode image size
     BitmapFactory.Options o = new BitmapFactory.Options();
     o.inJustDecodeBounds = true;
     BitmapFactory.decodeStream(new FileInputStream(f),null,o);

     //The new size we want to scale to
     final int REQUIRED_WIDTH=WIDTH;
     final int REQUIRED_HIGHT=HIGHT;
     //Find the correct scale value. It should be the power of 2.
     int scale=1;
     while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
         scale*=2;

     //Decode with inSampleSize
     BitmapFactory.Options o2 = new BitmapFactory.Options();
     o2.inSampleSize=scale;
     return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
 } catch (FileNotFoundException e) {}
 return null;
}
like image 83
Akash Moradiya Avatar answered Oct 20 '22 17:10

Akash Moradiya


BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(path,options);
like image 8
Biswajit Karmakar Avatar answered Oct 20 '22 17:10

Biswajit Karmakar