加载大图片内存溢出解决
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;
- }

浙公网安备 33010602011771号