2014-10-20 19 views
5

Khi tôi chọn hình ảnh từ thư viện nếu kích thước hình ảnh lớn hơn 3 Mb android OutOfMemoryError.OutOfMemoryError trong BitmapFactory.decodeFile()

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

Văn bản này từ nhật ký. Vui lòng giúp tôi, vì "thời hạn")

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) 
+1

Bạn cần phải mở rộng hình ảnh của bạn lúc đầu. –

+0

Viết nhận xét của bạn dưới dạng câu trả lời và nếu phương pháp này hoạt động - tôi kiểm tra câu trả lời của bạn dưới dạng intth – Artem

Trả lời

22

OutofMemory xảy ra khi ứng dụng của bạn vượt quá bộ nhớ được phân bổ trong heap. Các bitmap là quá lớn để phù hợp với bộ nhớ tức là đống. Trong trường hợp này, bạn hết bộ nhớ. Bạn cần phải giảm tỷ lệ bitmap và sau đó sử dụng như vậy.

For that check the link below

thử mã này có thể giúp bạn,

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

int cuối cùng REQUIRED_WIDTH = WIDTH; int cuối cùng REQUIRED_HIGHT = HIGHT; Điều đó có cần thiết không? –

4
BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inSampleSize = 8; 
Bitmap bm = BitmapFactory.decodeFile(path,options); 
Các vấn đề liên quan