`

【Android】如何解决bitmap 内存溢出out of memory的问题

阅读更多

很多人在android开发中都遇到了生成bitmap时候内存溢出,也就是out of memory(OOM)的问题,网上对这样的问题的的解决说法不一。笔者作为一个初级开发者,在这里向大家提供一种比较实用,比较易于理解的方法,这种方法不如一些高级开发者提出的方案来的深刻,但是也能帮助大家有效地解决问题。
废话不多说了,直接上代码。

BitmapFactory.Options opt = new BitmapFactory.Options(); 
               //这个isjustdecodebounds很重要	
               opt.inJustDecodeBounds = true;
               bm = BitmapFactory.decodeFile(absolutePath, opt);

               //获取到这个图片的原始宽度和高度
int picWidth  = opt.outWidth;
int picHeight = opt.outHeight;

               //获取屏的宽度和高度
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();

                //isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
opt.inSampleSize = 1;
                //根据屏的大小和图片大小计算出缩放比例
if(picWidth > picHeight){
if(picWidth > screenWidth)
opt.inSampleSize = picWidth/screenWidth;
}
else{
if(picHeight > screenHeight)

opt.inSampleSize = picHeight/screenHeight;
}

                //这次再真正地生成一个有像素的,经过缩放了的bitmap
opt.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(absolutePath, opt);

                //用imageview显示出bitmap
iv.setImageBitmap(bm);

 


inJustDecodeBounds 的介绍
public boolean inJustDecodeBounds
Since: API Level 1
If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.

就是说,如果设置
inJustDecodeBounds为true,仍可以获取到bitmap信息,但完全不用分配内存,因为没有获取像素,所以我们可以利用得到的Bitmap的大小,重新压缩图片,然后在内存中生成一个更小的Bitmap,这样即便是一个4MB的JPG,我们也可以随心所欲地把他压缩到任意大小,从而节省了内存,看到这里是不是恍然大悟,牛b了牛b了!

下面这个参数就是跟压缩图片有关的部分,很容易懂,不多解释了:


inSampleSize 的介绍
public int inSampleSize
Since: API Level 1
If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value

 

 

 

 

分享到:
评论
4 楼 sjl_008 2014-05-27  
有错误,inSampleSize 为2时,图片大小不是原来的2分之一。
inSampleSize 是将高度和宽度都缩小为原来的2分之一。
也就是说大仙变为原来的1/4了。
而且这个inSampleSize 也不是随便设置的。只能是2的n次方。如果不是,它会选择最接近的2次幂。例如设置的是3,则会选择2为标准。
3 楼 burnquist 2012-05-11  
> 应该是“>”符号吧,也就是大于号,是不是被编辑器给转换了?
codeMoe 写道
gt是什么变量

2 楼 codeMoe 2012-03-25  
gt是什么变量
1 楼 azulsidea 2011-11-23  

相关推荐

Global site tag (gtag.js) - Google Analytics