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

关于设置图片时,内存溢出的解决方法

2017-07-31 14:34 267 查看
不知道大家在使用ImageView的setImageBitmap方法时,有没有遇到过一旦给ImageView设置比较大的图片,就会导致内存溢出这样的问题。希望我所用的方法在一定程度上可以帮助大家~~
废话不多说,开始搞事情~~

/**
* 通过图片路径读取图片并通过对图片进行处理,从而减小图片的内存体积,避免内存溢出
* @param imgpath 需要处理的图片路径
* @param w 欲设定的宽度
* @param h 欲设定的高度
*/
public static Bitmap loadBitmap(String imgpath, int w, int h) {

BitmapFactory.Options opts = new BitmapFactory.Options();

//将option的injustDecodeBounds设为true时,解码bitmap时可以只返回它的宽、高和MIME类型,而不必为其申请内存,从而节省了内存空间。
opts.inJustDecodeBounds = true;

BitmapFactory.decodeFile(imgpath, opts);

//获取原图片的宽
int srcWidth = opts.outWidth;
//获取原图片的高
int srcHeight = opts.outHeight;

int destWidth = 0;
int destHeight = 0;
//缩放比例
double ratio = 0.0;

//原图的宽高其中一个小于预设值时,则选用原图的宽高
if (srcWidth < w || srcHeight < h) {
ratio = 0.0;
destWidth = srcWidth;
destHeight = srcHeight;
} else if (srcWidth > srcHeight) {
//原图的宽高都大于预设的宽高且宽的值比高的值要大,则选用宽的缩放比率
ratio = (double) srcWidth / w;
destWidth = w;
destHeight = (int) (srcHeight / ratio);
} else {
//原图的宽高都大于预设的宽高且高的值比宽的值要大,则选用高的缩放比率
ratio = (double) srcHeight / h;
destHeight = h;
destWidth = (int) (srcWidth / ratio);
}
//创建一个新的Options
BitmapFactory.Options newOpts = new BitmapFactory.Options();

//对图片的采样点进行隔行抽取,以减少图片的内存
newOpts.inSampleSize = (int) ratio + 1;

newOpts.inJustDecodeBounds = false;
newOpts.outHeight = destHeight;
newOpts.outWidth = destWidth;
通过新的配置好的options进行图片的解析
Bitmap tempBitmap = BitmapFactory.decodeFile(imgpath, newOpts);
return tempBitmap;
}


在此,对于inSampleSize进行说明一下:

对大图进行降采样,以减小内存占用。因为直接从点阵中隔行抽取最有效率,所以为了兼顾效率, inSampleSize 这个属性只认2的整数倍为有效.

比如你将 inSampleSize 赋值为2,那就是每隔2行采1行,每隔2列采一列,那你解析出的图片就是原图大小的1/4.

这个值也可以填写非2的倍数,非2的倍数会被四舍五入.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐