Android java.lang.OutOfMemoryError?

前端 未结 8 820
旧巷少年郎
旧巷少年郎 2020-12-08 16:24
04-25 08:19:10.111    2431-2603/com.example.francesco.guidedautorewithtabs E/art﹕ Throwing OutOfMemoryError \"Failed to allocate a 4194316 byte allocation with 19836         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 17:00

    This is because of low memory, size of your image file is large, to solve this problem add this method in your class:

    public static Bitmap decodeImageFile(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;
                }
    

    Then call this method where you using this:

    Bitmap b = decodeFile(f);
    

    use this insted:

    Bitmap b = decodeImageFile(f, 1280, 720);
    

提交回复
热议问题