android - BitmapFactory.decodeFile() 中的 OutOfMemoryError

标签 android bitmap out-of-memory

当我从图库中选取图像时,如果图像大小大于 3 Mb,android 会出现 OutOfMemoryError。

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

此文本来自日志。请帮助我,因为“最后期限”)

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)

最佳答案

OutofMemory 当您的应用超出堆中分配的内存时发生。位图太大,无法放入内存(即堆)中。在这种情况下,您会耗尽内存。您需要缩小位图,然后使用相同的位图。

For that check this link

试试这个代码可能对你有帮助,

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

关于android - BitmapFactory.decodeFile() 中的 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465281/

相关文章:

android - 动画 ImageView 色调属性从颜色到颜色

c++ - 进程外内存堆可在32位地址空间内工作

java - notifyDataSetChanged();未找到源异常

Android转换月份数组

Android:从我的 Activity 注册 BroadcastReceiver 并在我的应用程序未运行时保持其 Activity 状态

android - 如何构建 Android NDK 示例 : "bitmap-plasma"

java - 使用回收无效从 arraytlist 中清除位图,ANDROID

wpf - 从图像创建矢量

java - OutOfMemoryError 会导致线程死亡吗?

安卓 : java. lang.OutOfMemoryError : Failed to allocate with free bytes and 70MB until OOM when using gson. toJson()