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

Android Bitmap 用法大全,從此不再擔心

編輯:關於 Android 程式設計

Bitmap 是 Android 圖片處理的核心類別,但各種轉換場景(Drawable、byte[]、檔案、資源)散落在不同 API 裡,用時總要重新查。以下把常見用法整理成一份速查表。

1. Drawable → Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(
            drawable.getIntrinsicWidth(),
            drawable.getIntrinsicHeight(),
            drawable.getOpacity() != PixelFormat.OPAQUE
                    ? Bitmap.Config.ARGB_8888
                    : Bitmap.Config.RGB_565);

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);
    return bitmap;
}

這裡的 Config 選擇有講究:若 Drawable 不透明就用 RGB_565(每像素 2 位元組,省一半記憶體),否則用 ARGB_8888 保留透明通道。

2. 從資源取得 Bitmap

Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);

3. Bitmap → byte[]

private byte[] Bitmap2Bytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}

4. byte[] → Bitmap

private Bitmap Bytes2Bimap(byte[] b) {
    if (b.length != 0) {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    } else {
        return null;
    }
}

5. 儲存 Bitmap 為檔案

static boolean saveBitmap2file(Bitmap bmp, String filename) {
    CompressFormat format = Bitmap.CompressFormat.JPEG;
    int quality = 100;
    OutputStream stream = null;
    try {
        stream = new FileOutputStream("/sdcard/" + filename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return bmp.compress(format, quality, stream);
}

實際專案請改用 Environment.getExternalStorageDirectory() 或 App 專屬目錄 getExternalFilesDir(),並在 Android 10 以上採用 MediaStore 或 SAF,避免寫死路徑與要求 bulky 的儲存權限。

6. 依需求縮放圖片

// 讀取圖片來源
Bitmap bm = BitmapFactory.decodeStream(
        getResources().openRawResource(R.drawable.dog));

int width = bm.getWidth();
int height = bm.getHeight();

// 設定想要的尺寸
int newWidth = 320;
int newHeight = 480;

// 計算縮放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// 建立 Matrix 並設定縮放參數
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);

// 產生新的 Bitmap
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);

// 畫到畫布上
canvas.drawBitmap(newbm, 0, 0, paint);

7. 從檔案讀成 Bitmap

Bitmap bt = BitmapFactory.decodeFile("/sdcard/myImage/" + "head.jpg");

8. 從 drawable 資源讀成 Bitmap(可指定 raw 資源)

public Bitmap drawableToBitamp(int drawableResource) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.RGB_565;
    opt.inPurgeable = true;
    opt.inInputShareable = true;

    InputStream is = this.getResources().openRawResource(drawableResource);
    return BitmapFactory.decodeStream(is, null, opt);
}

額外補充:避免 OutOfMemoryError

以上都是基礎轉換,但真正在專案裡最常遇到的問題是記憶體。幾個實用技巧:

用 inSampleSize 做降採樣。這是控制解碼時記憶體占用的最有效手段:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;      // 第一次只讀尺寸,不配置像素記憶體
BitmapFactory.decodeFile(path, options);

int sampleSize = 1;
while (options.outWidth / (sampleSize * 2) > targetWidth
        && options.outHeight / (sampleSize * 2) > targetHeight) {
    sampleSize *= 2;
}

options.inSampleSize = sampleSize;
options.inJustDecodeBounds = false;     // 第二次才真正解碼
return BitmapFactory.decodeFile(path, options);

用 recycle() 明確釋放(Android 3.0 以下必要,之後 Bitmap 像素記憶體已改由 managed heap 配置,過度呼叫 recycle 反而容易造成使用已回收物件的 crash)。

善用複用池。inBitmap 可讓解碼時複用既有記憶體區塊,是 Android 4.4 之後降低 GC 抖動的關鍵設定:

options.inBitmap = reusableBitmap;
options.inMutable = true;

最後,若只是要在清單中顯示網路圖片,別自己折騰 BitmapFactory,直接用 Glide、Coil 或 Picasso,它們已把降採樣、快取、生命週期管理與 recycle 都處理妥當。

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