Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 圖片格式轉換:Bitmap、Drawable 與 byte[]

編輯:Android 開發實例

常見圖片型別

在 Android 開發中,常需要在 Bitmap、Drawable 與 byte[] 之間轉換。例如從資源取得圖片、將圖片顯示到 ImageView、上傳圖片到伺服器,或將圖片存入資料庫時,都會用到這些型別。

Drawable 轉 Bitmap

若要從資源取得 Bitmap,可直接使用:

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

若手上已有 Drawable,也可自行繪製到 Bitmap:

Bitmap bitmap = Bitmap.createBitmap(
    drawable.getIntrinsicWidth(),
    drawable.getIntrinsicHeight(),
    Bitmap.Config.ARGB_8888
);

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

Bitmap 轉 Drawable

Drawable drawable = new BitmapDrawable(bmp);

Bitmap 轉 byte[]

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();

byte[] 轉 Bitmap

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

注意事項

Bitmap 會佔用較多記憶體,若處理大量圖片,建議使用 sampledBitmap、物件池或圖片載入框架。此外,PNG 是無失真壓縮,JPEG 則不支援透明背景,選擇格式時需依需求決定。

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