加载大图片内存溢出解决

Android在加载大图片时,易出现内存溢出的情况,特别是在做多图浏览的时候。
如:Bitmap bitMap = BitmapFactory.decodeFile(file); 此种方式读取图片的时候就容易内存溢出(图片大小500k~~2M或更大)。如下给出解除此类问题的一种方法:

  1. // 按图片大小(字节大小)缩放图片
  2. public static Bitmap fitSizeImg(String path) {
  3. if(path == null || path.length()<1 ) return null;
  4. File file = new File(path);
  5. Bitmap resizeBmp = null;
  6. BitmapFactory.Options opts = new BitmapFactory.Options();
  7. // 数字越大读出的图片占用的heap越小 不然总是溢出
  8. if (file.length() < 20480) { // 0-20k
  9. opts.inSampleSize = 1;
  10. } else if (file.length() < 51200) { // 20-50k
  11. opts.inSampleSize = 2;
  12. } else if (file.length() < 307200) { // 50-300k
  13. opts.inSampleSize = 4;
  14. } else if (file.length() < 819200) { // 300-800k
  15. opts.inSampleSize = 6;
  16. } else if (file.length() < 1048576) { // 800-1024k
  17. opts.inSampleSize = 8;
  18. } else {
  19. opts.inSampleSize = 10;
  20. }
  21. resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts);
  22. return resizeBmp;
  23. }
posted @ 2012-08-31 12:30  囧里个囧  阅读(695)  评论(0)    收藏  举报