Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 大圖處理:位圖二次採樣壓縮(附源碼)

編輯:關於 Android 程式設計

圖片形狀各異、大小不一。在許多情況下,它們遠比我們的用戶介面(UI)要大得多,佔據著可觀的記憶體空間。如果不對位圖進行壓縮處理,程式很容易發生記憶體洩漏的錯誤。這時候,二次採樣(inSampleSize)就是我們的好幫手。

MainActivity 的程式碼:

package com.example.g08_bitmap;
import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class MainActivity extends Activity {
    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) this.findViewById(R.id.imageView1);
        imageView.setImageBitmap(decodeSampledBitmapFromResource(
                getResources(), R.drawable.a, 300, 300));
    }
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
            int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // 先將 inJustDecodeBounds 屬性設為 true,解碼時避免記憶體分配
        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 heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 選擇較小的比例作為壓縮比例
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}

這套做法的精髓在於:先把 inJustDecodeBounds 設為 true,讓解碼器只讀取圖片尺寸而不真正載入像素,據此算出合適的 inSampleSize,再關掉這個開關正式解碼。如此一來,既能大幅降低記憶體佔用,又能有效杜絕 OOM 風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved