Bitmap - Out of memory exception

前端 未结 5 1925
抹茶落季
抹茶落季 2021-01-25 04:46

When I try to get image from camera or gallery, I get error. Here is a part of logcat:

06-27 05:51:47.297: E/dalvikvm-heap(438): Out of memory on a 35295376-byte         


        
5条回答
  •  醉话见心
    2021-01-25 05:10

    You need to scale down your image.

    http://developer.android.com/training/displaying-bitmaps/load-bitmap.html.

    Use appropriate Bitmap.decode method and scale down the image.

    Bitmap.decode

    Example :

    Call the method with the required parameters.

    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;
    }
    

提交回复
热议问题