如: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;
}
opts.inSampleSize 指定加载图片时,按照原尺寸大小的高宽的1/inSampleSize大小缩放。
如果此值大于1,相当于缩小,小于1时放大。