今天遇见加载大图片是程序崩溃问题,发现 BitmapFactory.decodeFile 异常,内存溢出。

  在网上找到的一些资料与常用的优化办法,整理记录下。

感谢以下连接文章中的原作者!

http://chjmars.iteye.com/blog/1157137

http://www.cnblogs.com/hellope/archive/2011/08/23/2150400.html

http://blog.csdn.net/go_to_learn/article/details/9764805

http://blog.sina.com.cn/s/blog_4d6fba1b0100v9az.html


   使用android提供的BitmapFactory解码一张图片时,有时会遇到该错误,即:java.lang.OutOfMemoryError: bitmap size exceeds VM budget。这往往是由于图片过大造成的。要想正常使用,一种方式是分配更少的内存空间来存储,即在载入图片的时候以牺牲图片质量为代价,将图片进行放缩,这也是不少人现在为避免以上的OOM所采用的解决方法。但是,这种方法是得不偿失的,当我们使用图片作为缩略图查看时候倒是没有说什么,但是,当需要提供图片质量的时候,该怎么办呢?java.lang.OutOfMemoryError: bitmap size exceeds VM budget着实让不少人欲哭无泪呀!前几天刚好有个需求需要载入SD卡上面的图片。


一、options.inSampleSize

首先是使用

Bitmap bmp = BitmapFactory.decodeFile(pePicFile.getAbsolutePath() + "/"+info.getImage());

上面参数是我将要读取的图片文件及路径,当文件较小时,程序能够正常运行,但是当我选择一张大图时,程序立刻蹦出了java.lang.OutOfMemoryError: bitmap size exceeds VM budget的OOM错误!

在android设备上(where you have only 16MB memory available),如果使用BitmapFactory解码一个较大文件,很大的情况下会出现上述情况。那么,怎么解决?!

先说之前提到过的一种方法:即将载入的图片缩小,这种方式以牺牲图片的质量为代价。在BitmapFactory中有一个内部类BitmapFactory.Options,其中当options.inSampleSize值>1时,根据文档:

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. (1 -> decodes full size; 2 -> decodes 1/4th size; 4 -> decode 1/16th size). Because you rarely need to show and have full size bitmap images on your phone. For manipulations smaller sizes are usually enough.


也就是说,options.inSampleSize是以2的指数的倒数被进行放缩。这样,我们可以依靠inSampleSize的值的设定将图片放缩载入,这样一般情况也就不会出现上述的OOM问题了。现在问题是怎么确定inSampleSize的值?每张图片的放缩大小的比例应该是不一样的!这样的话就要运行时动态确定。在BitmapFactory.Options中提供了另一个成员inJustDecodeBounds。

1 2 3 BitmapFactory.Options opts = new  BitmapFactory.Options(); opts.inJustDecodeBounds = true ; Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);

设置inJustDecodeBounds为true后,decodeFile并不分配空间,但可计算出原始图片的长度和宽度,即opts.width和opts.height。有了这两个参数,再通过一定的算法,即可得到一个恰当的inSampleSize。Android提供了一种动态计算的方法。如下:

  1. /** 
  2.  * compute Sample Size 
  3.  *  
  4.  * @param options 
  5.  * @param minSideLength 
  6.  * @param maxNumOfPixels 
  7.  * @return 
  8.  */  
  9. public static int computeSampleSize(BitmapFactory.Options options,  
  10.         int minSideLength, int maxNumOfPixels) {  
  11.     int initialSize = computeInitialSampleSize(options, minSideLength,  
  12.             maxNumOfPixels);  
  13.   
  14.     int roundedSize;  
  15.     if (initialSize <= 8) {  
  16.         roundedSize = 1;  
  17.         while (roundedSize < initialSize) {  
  18.             roundedSize <<= 1;  
  19.         }  
  20.     } else {  
  21.         roundedSize = (initialSize + 7) / 8 * 8;  
  22.     }  
  23.   
  24.     return roundedSize;  
  25. }  
  26.   
  27. /** 
  28.  * compute Initial Sample Size 
  29.  *  
  30.  * @param options 
  31.  * @param minSideLength 
  32.  * @param maxNumOfPixels 
  33.  * @return 
  34.  */  
  35. private static int computeInitialSampleSize(BitmapFactory.Options options,  
  36.         int minSideLength, int maxNumOfPixels) {  
  37.     double w = options.outWidth;  
  38.     double h = options.outHeight;  
  39.   
  40.     // 上下限范围  
  41.     int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math  
  42.             .sqrt(w * h / maxNumOfPixels));  
  43.     int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(  
  44.             Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
  45.   
  46.     if (upperBound < lowerBound) {  
  47.         // return the larger one when there is no overlapping zone.  
  48.         return lowerBound;  
  49.     }  
  50.   
  51.     if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
  52.         return 1;  
  53.     } else if (minSideLength == -1) {  
  54.         return lowerBound;  
  55.     } else {  
  56.         return upperBound;  
  57.     }  
  58. }  
以上参考一下,我们只需要使用此函数就行了:

BitmapFactory.Options opts = new  BitmapFactory.Options(); opts.inJustDecodeBounds = true ; BitmapFactory.decodeFile(imageFile, opts);               opts.inSampleSize = computeSampleSize(opts, - 1 , 128 * 128 ); //这里一定要将其设置回false,因为之前我们将其设置成了true      opts.inJustDecodeBounds = false ; try  {      Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);      imageView.setImageBitmap(bmp);      } catch  (OutOfMemoryError err) {      }
 有了上面的算法,我们就可以轻易的get到Bitmap了:

  1. /** 
  2.  * get Bitmap 
  3.  *  
  4.  * @param imgFile 
  5.  * @param minSideLength 
  6.  * @param maxNumOfPixels 
  7.  * @return 
  8.  */  
  9. public static Bitmap tryGetBitmap(String imgFile, int minSideLength,  
  10.         int maxNumOfPixels) {  
  11.     if (imgFile == null || imgFile.length() == 0)  
  12.         return null;  
  13.   
  14.     try {  
  15.         FileDescriptor fd = new FileInputStream(imgFile).getFD();  
  16.         BitmapFactory.Options options = new BitmapFactory.Options();  
  17.         options.inJustDecodeBounds = true;  
  18.         // BitmapFactory.decodeFile(imgFile, options);  
  19.         BitmapFactory.decodeFileDescriptor(fd, null, options);  
  20.   
  21.         options.inSampleSize = computeSampleSize(options, minSideLength,  
  22.                 maxNumOfPixels);  
  23.         try {  
  24.             // 这里一定要将其设置回false,因为之前我们将其设置成了true  
  25.             // 设置inJustDecodeBounds为true后,decodeFile并不分配空间,即,BitmapFactory解码出来的Bitmap为Null,但可计算出原始图片的长度和宽度  
  26.             options.inJustDecodeBounds = false;  
  27.   
  28.             Bitmap bmp = BitmapFactory.decodeFile(imgFile, options);  
  29.             return bmp == null ? null : bmp;  
  30.         } catch (OutOfMemoryError err) {  
  31.             return null;  
  32.         }  
  33.     } catch (Exception e) {  
  34.         return null;  
  35.     }  
  36. }  

这样,在BitmapFactory.decodeFile执行处,也就不会报出上面的OOM Error了。完美解决?如前面提到的,这种方式在一定程度上是以牺牲图片质量为代价的。如何才能更加优化的实现需求?


二、BitmapFactory.decodeFileDescriptor

当在android设备中载入较大图片资源时,可以创建一些临时空间,将载入的资源载入到临时空间中。

1 2 BitmapFactory.Options bfOptions= new  BitmapFactory.Options(); bfOptions.inTempStorage= new  byte [ 12  * 1024 ];
以上创建了一个12kb的临时空间。然后使用Bitmap bitmapImage = BitmapFactory.decodeFile(path,bfOptions);但是我在程序中却还是出现以上问题!以下使用BitmapFactory.decodeFileDescriptor解决了以上问题:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 BitmapFactory.Options bfOptions= new  BitmapFactory.Options();               bfOptions.inDither= false ;//使图片不抖动。不是很懂                                  bfOptions.inPurgeable= true ; //使得内存可以被回收                           bfOptions.inTempStorage= new  byte [ 12  * 1024 ];//临时存储              // bfOptions.inJustDecodeBounds = true;               File file = new  File(pePicFile.getAbsolutePath() + "/" +info.getImage());               FileInputStream fs= null ;               try  {                  fs = new  FileInputStream(file);              } catch  (FileNotFoundException e) {                  e.printStackTrace();              }               Bitmap bmp = null ;               if (fs != null )                  try  {                      bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null , bfOptions);                  } catch  (IOException e) {                      e.printStackTrace();                  } finally {                      if (fs!= null ) {                          try  {                              fs.close();                          } catch  (IOException e) {                              e.printStackTrace();                          }                      }                  }

当然要将取得图片进行放缩显示等处理也可以在以上得到的bmp进行。
PS:请图片处理后进行内存回收。 bmp.recycle();这样将图片占有的内存资源释放。


三、BitmapFactory 方法:decodeFileDescriptor()、decodeFile()比较

decodeFileDescriptor()来生成bimap比decodeFile()省内存

[java]  view plain copy
  1. FileInputStream is = = new FileInputStream(path);  
替换:

[java]  view plain copy
  1. Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts);  
  2.    imageView.setImageBitmap(bmp);  
原因:
查看BitmapFactory的源码,对比一下两者的实现,可以发现decodeFile()最终是以流的方式生成bitmap 

decodeFile源码:

[java]  view plain copy
  1. public static Bitmap decodeFile(String pathName, Options opts) {  
  2.     Bitmap bm = null;  
  3.     InputStream stream = null;  
  4.     try {  
  5.         stream = new FileInputStream(pathName);  
  6.         bm = decodeStream(stream, null, opts);  
  7.     } catch (Exception e) {  
  8.         /*  do nothing. 
  9.             If the exception happened on open, bm will be null. 
  10.         */  
  11.     } finally {  
  12.         if (stream != null) {  
  13.             try {  
  14.                 stream.close();  
  15.             } catch (IOException e) {  
  16.                 // do nothing here  
  17.             }  
  18.         }  
  19.     }  
  20.     return bm;  
  21. }  

decodeFileDescriptor的源码,可以找到native本地方法decodeFileDescriptor,通过底层生成bitmap

decodeFileDescriptor源码:

[java]  view plain copy
  1.    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {  
  2.        if (nativeIsSeekable(fd)) {  
  3.            Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);  
  4.            if (bm == null && opts != null && opts.inBitmap != null) {  
  5.                throw new IllegalArgumentException("Problem decoding into existing bitmap");  
  6.            }  
  7.            return finishDecode(bm, outPadding, opts);  
  8.        } else {  
  9.            FileInputStream fis = new FileInputStream(fd);  
  10.            try {  
  11.                return decodeStream(fis, outPadding, opts);  
  12.            } finally {  
  13.                try {  
  14.                    fis.close();  
  15.                } catch (Throwable t) {/* ignore */}  
  16.            }  
  17.        }  
  18.    }  
  19.   
  20. private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts);  


四、补充说明

1,

android系统的手机在系统底层指定了堆内存的上限值,大部分手机的缺省值是16MB,不过也有些高配置的机型是24MB的,所以我们的程序在申请内存空间时,为了确保能够成功申请到内存空间,应该保证当前已分配的内存加上当前需要分配的内存值的总大小不能超过当前堆的最大内存值,而且内存管理上将外部内存完全当成了当前堆的一部分,也就是说Bitmap对象通过栈上的引用来指向堆上的Bitmap对象,而堆上的Bitmap对象又对应了一个使用了外部存储的native图像,也就是实际上使用的字节数组byte[]来存储的位图信息,因此解码之后的Bitmap的总大小就不能超过8M了。
解决这类问题的最根本的,最有效的办法就是,使用完bitmap之后,调用bitmap对象的recycle()方法释放所占用的内存,以便于下一次使用。


2,

设置系统的最小堆大小

int newSize = 4 * 1024 * 1024 ; //设置最小堆内存大小为4MB
VMRuntime.getRuntime().setMinimumHeapSize(newSize);
VMRuntime.getRuntime().setTargetHeapUtilization(0.75); // 设置堆内存的利用率为75%
堆(HEAP)是VM中占用内存最多的部分,通常是动态分配的。堆的大小不是一成不变的,当堆内存实际的利用率偏离设定的值的时候,虚拟机会在GC的时候调整堆内存大小,让实际占用率向个百分比靠拢。比如初始的HEAP是4M大小,当4M的空间被占用超过75%的时候,重新分配堆为8M大;当8M被占用超过75%,分配堆为16M大。倒过来,当16M的堆利用不足30%的时候,缩减它的大小为8M大。重新设置堆的大小,尤其是压缩,一般会涉及到内存的拷贝,所以变更堆的大小对效率有不良影响。

3,

BitmapFactory? .Options options = new BitmapFactory? .Options();
options.inTempStorage = new byte[1024*1024*5]; //5MB的临时存储空间
Bitmap bm = BitmapFactory? .decodeFile("/mnt/sdcard/a.jpg",options);
补充说明:从创建Bitmap的C++底层代码BitmapFactory.cpp中的处理逻辑来看,如果option不为null的话,那么会优先处理option中设置的各个参数,假设当前你设置option的inTempStorage为1024*1024*4(4M)大小的话,而且每次解码图像时均使用该option对象作为参数,那么你的程序极有可能会提前失败,经过测试,如果使用一张大小为1.03M的图片来进行解码,如果不使用option参数来解码,可以正常解码四次,也就是分配了四次内存,而如果使用option的话,就会出现内存溢出错误,只能正常解码两次。Options类有一个预处理参数,当你传入options时,并且指定临时使用内存大小的话,Android将默认先申请你所指定的内存大小,如果申请失败,就会先抛出内存溢出错误。而如果不指定内存大小,系统将会自动计算,如果当前还剩3M空间大小,而解码只需要2M大小,那么在缺省情况下将能解码成功,而在设置inTempStorage大小为4M的情况下就将出现内存溢出错误。所以,通过设置Options的inTempStorage大小也不能从根本上解决大图像解码的内存溢出问题。
总之再做android开发时,出现内存溢出是属于系统底层限制,只要解码需要的内存超过系统可分配的最大内存值,那么内存溢出错误必然会出现。


更多相关文章

  1. 谁是最受欢迎的Linux发行版?
  2. Android如何获取SDCard 内存
  3. Android(安卓)Studio提高效率插件---adb idea
  4. android jar包
  5. android Activity的四种启动模式
  6. Android(安卓)OOM ,回收布局文件中ImageView占用的内存.Bitmap O
  7. android Menory 小结
  8. android仿苹果弹性布局
  9. 寻找android中的设计模式(三)

随机推荐

  1. Android线程阻塞处理及优化
  2. 【Android系统源码修改】在系统设置中添
  3. Android(安卓)UI设计的FrameLayout与Tabl
  4. 高德天气应用开发之二:android 高德天气AP
  5. Mono For Android离线激活
  6. Android自定义背景的设置方法
  7. Android用户界面 UI组件--AdapterView及
  8. Android日志(Log类)
  9. Android仿百度谷歌搜索自动提示框AutoCom
  10. Android、JUnit深入浅出(一)——JUnit初步