您的位置:首页 > 移动开发 > Android开发

Android在加载大图片时,易出现内存溢出的情况 解决方案一

2012-06-11 10:51 267 查看
转:http://www.maxiaoguo.com/shipin/324.html

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;

}

opts.inSampleSize 指定加载图片时,按照原尺寸大小的高宽的1/inSampleSize大小缩放。

如果此值大于1,相当于缩小,小于1时放大。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: