1. 在Android軟件開(kāi)發(fā)過(guò)程中,圖片處理是經(jīng)常遇到的。 在將圖片轉(zhuǎn)換成Bitmap的時(shí)候,由于圖片的大小不一樣,當(dāng)遇到很大的圖片的時(shí)候會(huì)出現(xiàn)超出內(nèi)存的問(wèn)題,為了解決這個(gè)問(wèn)題Android API提供了BitmapFactory.Options這個(gè)類(lèi).
2. 由于Android對(duì)圖片使用內(nèi)存有限制,若是加載幾兆的大圖片便內(nèi)存溢出。Bitmap會(huì)將圖片的所有像素(即長(zhǎng)x寬)加載到內(nèi)存中,如果圖片分辨率過(guò)大,會(huì)直接導(dǎo)致內(nèi)存OOM,只有在BitmapFactory加載圖片時(shí)使用BitmapFactory.Options對(duì)相關(guān)參數(shù)進(jìn)行配置來(lái)減少加載的像素。
3. BitmapFactory.Options相關(guān)參數(shù)詳解:
(1).Options.inPreferredConfig值來(lái)降低內(nèi)存消耗。
比如:默認(rèn)值A(chǔ)RGB_8888改為RGB_565,節(jié)約一半內(nèi)存。
(2).設(shè)置Options.inSampleSize 縮放比例,對(duì)大圖片進(jìn)行壓縮 。
(3).設(shè)置Options.inPurgeable和inInputShareable:讓系統(tǒng)能及時(shí)回 收內(nèi)存。
A:inPurgeable:設(shè)置為T(mén)rue時(shí),表示系統(tǒng)內(nèi)存不足時(shí)可以被回 收,設(shè)置為False時(shí),表示不能被回收。
B:inInputShareable:設(shè)置是否深拷貝,與inPurgeable結(jié)合使用,inPurgeable為false時(shí),該參數(shù)無(wú)意義。
(4).使用decodeStream代替其他方法。
decodeResource,setImageResource,setImageBitmap等方法
4.代碼部分:
public static Bitmap getBitmapFromFile(File file, int width, int height) { BitmapFactory.Options opts = null; if (null != file && file.exists()) { if (width > 0 && height > 0) { opts = new BitmapFactory.Options(); // 只是返回的是圖片的寬和高,并不是返回一個(gè)Bitmap對(duì)象 opts.inJustDecodeBounds = true; // 信息沒(méi)有保存在bitmap里面,而是保存在options里面 BitmapFactory.decodeFile(file.getPath(), opts); // 計(jì)算圖片縮放比例 final int minSideLength = Math.min(width, height); // 縮略圖大小為原始圖片大小的幾分之一。根據(jù)業(yè)務(wù)需求來(lái)做。 opts.inSampleSize = computeSampleSize(opts, minSideLength, width * height); // 重新讀入圖片,注意此時(shí)已經(jīng)把options.inJustDecodeBounds設(shè)回false opts.inJustDecodeBounds = false; // 設(shè)置是否深拷貝,與inPurgeable結(jié)合使用 opts.inInputShareable = true; // 設(shè)置為T(mén)rue時(shí),表示系統(tǒng)內(nèi)存不足時(shí)可以被回 收,設(shè)置為False時(shí),表示不能被回收。 opts.inPurgeable = true; } try { return BitmapFactory.decodeFile(file.getPath(), opts); } catch (OutOfMemoryError e) { e.printStackTrace(); } } return null; }
|
新聞熱點(diǎn)
疑難解答
圖片精選