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

Android 圖片縮放與指定尺寸載入

編輯:關於 Android 程式設計

在 Android 中處理圖片時,經常需要縮放尺寸。若圖片過大,直接載入可能造成記憶體浪費,甚至引發 OOM。常見做法有兩種:使用 Matrix 縮放,或使用 inSampleSize 降低解碼大小。

使用 Matrix 縮放

若已經有 Bitmap,可以使用 Matrix 對它進行縮放。

public static Drawable resizeImage(Bitmap bitmap, int w, int h) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    float scaleWidth = ((float) w) / width;
    float scaleHeight = ((float) h) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    return new BitmapDrawable(resizedBitmap);
}

使用 inSampleSize 縮放

若圖片來自檔案,可以先只讀取尺寸資訊,再決定合適的 inSampleSize,避免一次載入過大圖片。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

int outWidth = options.outWidth;
int outHeight = options.outHeight;

options.inSampleSize = calculateSampleSize(outWidth, outHeight, width, height);
options.inJustDecodeBounds = false;

return new BitmapDrawable(BitmapFactory.decodeFile(path, options));

兩種方式的差異

Matrix 縮放適合已在記憶體中的 Bitmap,但原始圖片仍可能已佔用大量記憶體。inSampleSize 則是在解碼階段就降低影像尺寸,對大圖優化更明顯。

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