|
很多人在android开发中都遇到了生成bitmap时候内存溢出,也就是out of memory(OOM)的问题,网上对这样的问题的的解决说法不一。笔者作为一个初级开发者,在这里向大家提供一种比较实用,比较易于理解的方法,这种方法不如一些高级开发者提出的方案来的深刻,但是也能帮助大家有效地解决问题。
废话不多说了,直接上代码。
java代码 <span style="font-size: small;">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);</span>
复制代码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.
就是说,如果设置成true,仍可以访问获取到bitmap信息,而不用分配内存,因为没有获取像素
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 <= 1 is treated the same as 1. Note: the decoder will try to fulfill this request, but the resulting bitmap may have different dimensions that precisely what has been requested. Also, powers of 2 are often faster/easier for the decoder to honor.
这个更容易理解了,不多说了,不过要注意,如果inSampleSize 设置为2,那么生成bitmap的长和宽都为原始的1/2,则图片的像素数量就变为以前的1/4了 |
|