Android開發之Bitmap的高效載入

來源:互聯網
上載者:User

標籤:

BitmapFactory類提供了四類方法:decodeFile, decodeResource, decodeStream和decodeByteArray

分別用於支援從檔案系統,資源,輸入資料流以及位元組數組中載入出一個Bitmap對象,前兩者又間接調用了decodeStream

為了避免OOM,可以通過採樣率有效載入圖片

如果擷取採樣率?

1.將BitmapFactory.Options的inJustDecodeBounds的參數設定為true並載入圖片

2.從BitmapFactory.Options中取出圖片的原始寬高,它們對應outWidth和outHeight參數

3.根據採樣率的規則並結合目標View的所需大小計算採樣率inSampleSize

4.將BitmapFactory.Options的inJustDecodeBounds的參數設定為false,並重新載入圖片

上述步驟通過代碼體現:

public static Bitmap decodeSampledBitmapFromResource(Resource res, int resId, int reqWidth, int reqHeight){    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResource(res, resId, options);        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);    options.inJustDecodeBounds = false;    return BitmapFactory.decodeResource(res, resId, options);}public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){    final int height = options.outHeight;    final int width = options.outWidth;    int inSampleSize = 1;    if(height > reqHeight || width > reqWidth){        final int halfHeight = height / 2;        final int halfWidth = width / 2;                while((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth){            inSampleSize *= 2;                    }    }        return inSampleSize;}

 

Android開發之Bitmap的高效載入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.