美文网首页
Android加载图片时OOM异常解决办法——Bitmap Op

Android加载图片时OOM异常解决办法——Bitmap Op

作者: 小凯晨风 | 来源:发表于2017-07-14 11:32 被阅读0次

在Android里加载图片,通常转换成Bitmap对象,如果图片过大,就会引起OOM异常,所以Android提供了 BitmapFactory.Options类,

把inJustDecodeBounds  设置为true,返回的bitmap为null,但是会把Bitmap的宽高返回,这样就避免的OOM异常

BitmapFactory.Options options =newBitmapFactory.Options();options.inJustDecodeBounds =true;Bitmap bmp = BitmapFactory.decodeFile(path, options);/* 这里返回的bmp是null */

得到了宽高后,要压缩图片

intheight = options.outHeight *200/ options.outWidth;options.outWidth =200;options.outHeight = height; options.inJustDecodeBounds =false;Bitmap bmp = BitmapFactory.decodeFile(path, options);image.setImageBitmap(bmp);

这样并没有有效的节约内存。要想节约内存,还需要用到BitmapFactory.Options这个类里的inSampleSize这个成员变量。

我们可以根据图片实际的宽高和我们期望的宽高来计算得到这个值。

options.inSampleSize = options.outWidth /200;/*图片长宽方向缩小倍数*/

另外,为了节约内存我们还可以使用下面的几个字段:

options.inDither=false;/*不进行图片抖动处理*/options.inPreferredConfig=null;/*设置让解码器以最佳方式解码*//* 下面两个字段需要组合使用 */options.inPurgeable =true;options.inInputShareable =true;

相关文章

网友评论

      本文标题:Android加载图片时OOM异常解决办法——Bitmap Op

      本文链接:https://www.haomeiwen.com/subject/almnhxtx.html