不少人在android開發中都遇到了生成bitmap時候內存溢出,也就是out of memory(OOM)的問題,網上對這樣的問題的的解決說法不一。筆者做爲一個初級開發者,在這裏向你們提供一種比較實用,比較易於理解的方法,這種方法不如一些高級開發者提出的方案來的深入,可是也能幫助你們有效地解決問題。
廢話很少說了,直接上代碼。android
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了!spa
下面這個參數就是跟壓縮圖片有關的部分,很容易懂,很少解釋了:code
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 valueblog
REFERENCES:http://moto0421.iteye.com/blog/1153657圖片