加载图片时节约内存方法

来源:互联网 发布:大数据分析技术方案 编辑:程序博客网 时间:2024/05/01 22:54

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

 
// 按图片大小(字节大小)缩放图片
 public static Bitmap fitSizeImg(String path) {
  if(path == null || path.length()<1 ) return null;
  File file = new File(path);
  Bitmap resizeBmp = null;
  BitmapFactory.Options opts = new BitmapFactory.Options();
  // 数字越大读出的图片占用的heap越小 不然总是溢出
  if (file.length() < 20480) {       // 0-20k
   opts.inSampleSize = 1;
  } else if (file.length() < 51200) { // 20-50k
   opts.inSampleSize = 2;
  } else if (file.length() < 307200) { // 50-300k
   opts.inSampleSize = 4;
  } else if (file.length() < 819200) { // 300-800k
   opts.inSampleSize = 6;
  } else if (file.length() < 1048576) { // 800-1024k
   opts.inSampleSize = 8;
  } else {
   opts.inSampleSize = 10;
  }
  resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts);
  return resizeBmp;
 }

原创粉丝点击