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

Android:檢查 ImageView 是否載入成功,並整理 Bitmap 型別轉換

編輯:關於 Android 程式設計

判斷圖片是否載入成功

網路圖片載入失敗是很常見的情況。與其留一片空白,不如在偵測到沒有 Drawable 時換上預設佔位圖:

if (mPhotoView.getDrawable() == null) {
    // Toast.makeText(getActivity(), "圖片載入失敗", Toast.LENGTH_SHORT).show();
    mPhotoView.setImageDrawable(
            getResources().getDrawable(R.drawable.icon_default_user_photo));
}

實務上更完整的做法是在圖片載入框架的失敗回呼中設定佔位圖,而不是事後才檢查;因為 getDrawable() 為 null 也可能只是「還沒載完」,此時直接換成預設圖反而會蓋掉稍後成功的結果。

Bitmap、Drawable、byte[]、資源 id 之間的轉換

1. Bitmap → byte[]

ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] array = out.toByteArray();

2. byte[] → Bitmap

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

3. Bitmap → Drawable

Drawable drawable = new FastBitmapDrawable(bitmap);

4. Drawable → Bitmap

若是 BitmapDrawable 或 FastBitmapDrawable,直接取 getBitmap 即可;其他類型的 Drawable 則要畫到一個新的 Bitmap 上:

Bitmap bitmap = Bitmap.createBitmap(
        drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
        Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);

5. 資源 id → Drawable

Drawable drawable = activity.getResources().getDrawable(R.drawable.icon);

6. 資源 id → Bitmap

Bitmap bitmap = BitmapFactory.decodeResource(resources, id);

幾個實務提醒

  • decodeResource 會依螢幕密度自動縮放,decodeResourceStream 與 decodeFile 則不會,跨密度處理圖片時這個差異容易造成尺寸不如預期。
  • 用 PNG 壓縮成 byte[] 時第二個參數(品質)實際上無效,PNG 是無失真格式;只有 JPEG 才吃這個參數。
  • 大量轉換時盡量避免反覆建立 ByteArrayOutputStream,並在不需要時及早呼叫 recycle() 釋放 Bitmap。
  • getDrawable() 在 API 22 以上已標記為 deprecated,建議改用 ContextCompat.getDrawable(context, id) 以相容不同版本。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved