欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android Bitmap壓縮方式分析

 更新時間:2017年07月15日 11:45:45   作者:左手木亽  
這篇文章主要介紹了Android Bitmap壓縮方式分析的相關(guān)資料,需要的朋友可以參考下

Android Bitmap壓縮方式分析

在網(wǎng)上調(diào)查了圖片壓縮的方法并實(shí)裝后,大致上可以認(rèn)為有兩類壓縮:質(zhì)量壓縮(不改變圖片的尺寸)和尺寸壓縮(相當(dāng)于是像素上的壓縮);質(zhì)量壓縮一般可用于上傳大圖前的處理,這樣就可以節(jié)省一定的流量,畢竟現(xiàn)在的手機(jī)拍照都能達(dá)到3M左右了,尺寸壓縮一般可用于生成縮略圖。

在Android開發(fā)中我們都會遇到在一個100*100的ImageView上顯示一張過大的圖片,如果直接把這張圖片顯示上去對我們應(yīng)用沒有一點(diǎn)好處反而存在OOM的危險(xiǎn),所以我們有必要采用一種有效壓縮方式來顯示上去。

private void calculateBitmapInSimpleSize() {
    Bitmap _bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage);
    getBitmapDatas(_bitmap);

    BitmapFactory.Options optioins = new BitmapFactory.Options();
    optioins.inJustDecodeBounds = true;
//    optioins.inPreferredConfig = Bitmap.Config.RGB_565;//11158560
    optioins.inPreferredConfig = Bitmap.Config.ARGB_8888;//22317120
    BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
    int reqWidth = optioins.outWidth;
    int reqHeight = optioins.outHeight;

    Log.w(TAG, "reqWidth = " + reqWidth);
    Log.w(TAG, "reqHeight = " + reqHeight);

    int inSampleSize = 1;
    final int widthRatio = Math.round((float)reqWidth / 100f);
    final int heigthRatio = Math.round((float) reqHeight / 100f);
    // 取最小值 這將保證壓縮出來的圖片大于或者等于請求的寬度或者高度
    inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;
    Log.w(TAG, "first inSampleSize = " + inSampleSize);

    final int totalPixel = 100 * 100;
    final int totalReqPixel = reqWidth * reqHeight * 2;

    Log.w(TAG, "totalReqPixel = " + totalReqPixel);

    while (totalPixel / (inSampleSize * inSampleSize) > totalReqPixel) {
      Log.w(TAG, "totalPixel = " + (totalPixel / (inSampleSize * inSampleSize)));
      inSampleSize ++;
    }

    Log.w(TAG, "LastInSampleSize = " + inSampleSize);

    optioins.inJustDecodeBounds = false;

    Bitmap lastBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins);
    getBitmapDatas(lastBitmap);

    mImageView.setImageBitmap(lastBitmap);

  }

通過打印log我們可以清楚發(fā)現(xiàn)一張?jiān)嫉膱D片占有22317120字節(jié),經(jīng)過壓縮后11158560(RGB_565)/ 22317120(RGB8888)明顯所占用的內(nèi)存都減少了,盡量降低這種情況帶來的OOM。

做法:

1.optioins.inJustDecodeBounds = true設(shè)置為true可用于讀取該bitmap的寬高且不會占用內(nèi)存。

2.optioins.inPreferredConfig = Bitmap.Config.RGB_565設(shè)置在內(nèi)存中以占用最少的方式,相比RGB_8888只有其一半的內(nèi)存占有。

3.final int widthRatio = Math.round((float)reqWidth / 100f);
final int heigthRatio = Math.round((float) reqHeight / 100f);
inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;

計(jì)算壓縮比例,取最小值 這將保證壓縮出來的圖片大于或者等于請求的寬度或者高度。

4.在要顯示到ImageView的時候optioins.inJustDecodeBounds = false設(shè)回false這樣就能正常顯示了

// 計(jì)算bitmap所占內(nèi)存值
 public void getBitmapDatas(Bitmap bitmap) {
     Log.w(TAG, "Bitmap size = " + bitmap.getByteCount());
  }

采用以上的壓縮方式 我們就能避免一張過大的圖片”浪費(fèi)”的顯示在ImageView上造成內(nèi)存消耗過大。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

最新評論