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

Android 在 Activity 之間傳遞圖片(Bitmap)的方法

編輯:關於 Android 程式設計

Activity 之間傳遞參數是日常開發的基本功,用 Intent.putExtra() 傳字串、傳數字都很直覺。但如果要傳的是一張圖片呢?關鍵在於 Bitmap 已經實作了 Parcelable 介面,所以同樣可以用 putExtra() 塞進 Intent 裡。以下用一個「點擊圖片後跳轉並放大顯示」的小例子說明。

一、MainActivity:點擊圖片並送出

版面中放一個 ImageView,在 onCreate() 中載入一張本地圖片:

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

接著在點擊監聽器中建立 Intent 並附帶該 Bitmap:

Intent intent = new Intent(MainActivity.this, TranActivity.class);
intent.putExtra("bitmap", bitmap);
startActivity(intent);

就這樣,點擊圖片後便會跳轉到 TranActivity,並把 Bitmap 作為參數一起帶過去。

二、TranActivity:接收並顯示

imageview = (ImageView) findViewById(R.id.trans_imageview);
Intent intent = getIntent();
if (intent != null) {
    bitmap = intent.getParcelableExtra("bitmap");
    imageview.setImageBitmap(bitmap);
}

用 getIntent() 取得呼叫方傳來的 Intent,再以 getParcelableExtra() 取出 Bitmap,最後交給 ImageView 顯示。這裡的 intent != null 判斷是必要的防禦——若這個 Activity 也可能由其他路徑啟動(例如系統通知、Deep Link),Intent 裡就不會有我們的資料。

三、接收後放大 1.5 倍

要在顯示時做縮放,可以透過 Matrix 搭配 Bitmap.createBitmap() 產生一張新的點陣圖:

imageview = (ImageView) findViewById(R.id.trans_imageview);
Intent intent = getIntent();
if (intent != null) {
    bitmap = intent.getParcelableExtra("bitmap");
    Matrix matrix = new Matrix();   // 接收圖片後放大 1.5 倍
    matrix.postScale(1.5f, 1.5f);
    Bitmap bit = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
            bitmap.getHeight(), matrix, true);
    imageview.setImageBitmap(bit);
}

createBitmap() 的最後一個參數 filter 設為 true 會啟用雙線性濾波,放大後的邊緣會平滑一些;若追求像素風的銳利效果則可設為 false。

執行結果

TranActivity,放大之後的效果:

這種做法的界線在哪裡

用 Intent 傳 Bitmap 能跑,但並不適合正式專案,原因有幾個:

  • 大小受限。Intent 透過 Binder 傳遞,而 Binder 的緩衝區每個行程只有約 1MB,且是與其他 Binder 呼叫共用的。傳一張稍大的圖片就會引發 TransactionTooLargeException。實務上應該先縮圖,或乾脆不要這樣傳。
  • 會多一份記憶體副本。Parcelable 的序列化/反序列化過程會產生新的物件,等於同一張圖在記憶體裡存在兩份,在堆空間有限的裝置上相當奢侈。
  • 更合適的替代方案:
    • 只傳 URI(例如 FileProvider 產生的 content:// 位址),由接收方自行按需載入。
    • 把圖片寫入檔案或 Cache 目錄,只傳路徑字串。
    • 若只是要在同一個 Activity 內切換畫面,用 Fragment 或共享的 ViewModel 反而更直接。

而如果只是想縮放顯示,其實不必重新產生 Bitmap——直接在 XML 上設定 android:scaleType 與 android:scaleX/scaleY,或由程式呼叫 setScaleX()、setScaleY(),就能省下一整張點陣圖的配置成本。

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