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

安卓開發技巧:Bitmap、Drawable 與 byte[] 的相互轉換

編輯:關於 Android 開發

在 Android 開發中,圖像處理經常需要在 Bitmap、Drawable 與 byte[] 之間轉換,例如將圖片存進資料庫或自網路傳輸時。以下整理幾種常見的轉換寫法。

Drawable 與 Bitmap 互轉

最簡單的方式是透過資源直接解碼,再反之包裝:

 // Drawable → Bitmap Resources res=getResources(); Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.sample_0); // Bitmap → Drawable Drawable drawable = new BitmapDrawable(bmp);

更通用的 Drawable → Bitmap

若手邊已有一個 Drawable 物件,可新建一張同尺寸的 Bitmap,再讓 Drawable 繪製到 Canvas 上:

 public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap.Config config; if (drawable.getOpacity() != PixelFormat.OPAQUE) { config = Bitmap.Config.ARGB_8888; } else { config = Bitmap.Config.RGB_565; } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), config); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }

這裡依 Drawable 是否為不透明來選擇 ARGB_8888 或 RGB_565,兼顧畫質與記憶體用量。

Bitmap 與 byte[] 互轉

要將 Bitmap 轉為位元組陣列,可先壓縮到 ByteArrayOutputStream:

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

反之,要從位元組陣列還原成 Bitmap,則用 decodeByteArray:

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

掌握這幾組轉換,無論是將圖片存入 SQLite、上傳到伺服器,或從網路載入後顯示,都能得心應手。

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