很多人在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
REFERENCES:http://moto0421.iteye.com/blog/1153657