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

Android 圖形資料互轉工具類:Bitmap、Drawable、byte[] 與 InputStream 一次搞懂

編輯:關於 Android 程式設計

在 Android 開發裡,圖片資料會以好幾種姿態出現:記憶體中的 Bitmap、可繪製的 Drawable、適合網路傳輸與資料庫儲存的 byte[],以及串流形式的 InputStream。這四者之間的轉換幾乎每個專案都會遇到,與其到處寫臨時程式碼,不如收攏成一個工具類。

轉換關係一張圖看懂

核心樞紐是 Bitmap。其他型別要互相轉換,基本上都先轉成 Bitmap 再轉出去:

  • Bitmap ⇄ byte[]:靠 ByteArrayOutputStream + compress(),以及 BitmapFactory.decodeByteArray()。
  • Bitmap ⇄ InputStream:同樣先壓縮進 ByteArrayOutputStream,再包成 ByteArrayInputStream。
  • Drawable → Bitmap:建立同尺寸的 Bitmap 與 Canvas,把 Drawable 畫上去。
  • Bitmap → Drawable:用 BitmapDrawable 包一層即可。

工具類實作

package com.soai.imdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class FormatTools {

    private static FormatTools tools = new FormatTools();

    public static FormatTools getInstance() {
        return tools;
    }

    /** byte[] 轉 InputStream */
    public InputStream Byte2InputStream(byte[] b) {
        return new ByteArrayInputStream(b);
    }

    /** InputStream 轉 byte[](正確寫法:直接收集位元組,不要經過 String) */
    public byte[] InputStream2Bytes(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int readCount;
        while ((readCount = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, readCount);
        }
        return baos.toByteArray();
    }

    /** Bitmap 轉 InputStream(JPEG,預設品質) */
    public InputStream Bitmap2InputStream(Bitmap bm) {
        return Bitmap2InputStream(bm, 100);
    }

    /** Bitmap 轉 InputStream(可指定格式與品質) */
    public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
        return new ByteArrayInputStream(baos.toByteArray());
    }

    /** InputStream 轉 Bitmap */
    public Bitmap InputStream2Bitmap(InputStream is) {
        return BitmapFactory.decodeStream(is);
    }

    /** Drawable 轉 InputStream */
    public InputStream Drawable2InputStream(Drawable d) {
        return Bitmap2InputStream(drawable2Bitmap(d));
    }

    /** InputStream 轉 Drawable */
    public Drawable InputStream2Drawable(InputStream is) {
        return bitmap2Drawable(InputStream2Bitmap(is));
    }

    /** Drawable 轉 byte[] */
    public byte[] Drawable2Bytes(Drawable d) {
        return Bitmap2Bytes(drawable2Bitmap(d));
    }

    /** byte[] 轉 Drawable */
    public Drawable Bytes2Drawable(byte[] b) {
        return bitmap2Drawable(Bytes2Bitmap(b));
    }

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

    /** byte[] 轉 Bitmap */
    public Bitmap Bytes2Bitmap(byte[] b) {
        if (b != null && b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        }
        return null;
    }

    /** Drawable 轉 Bitmap */
    public Bitmap drawable2Bitmap(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;
    }

    /** Bitmap 轉 Drawable */
    public Drawable bitmap2Drawable(Bitmap bitmap) {
        return new BitmapDrawable(bitmap);
    }
}

幾個實務上會踩到的細節

不要讓 byte[] 經過 String。 常見的錯誤寫法是把每次 read 到的內容 new String(...) 再用字串相加拼回去,最後 getBytes()。圖片是二進位資料,經過字元編碼解碼會被破壞,而且字串相加在迴圈中會產生大量暫存物件。正確做法就是上面那樣直接寫進 ByteArrayOutputStream。

記得關流。 InputStream 用完要 close,或改用 try-with-resources,避免檔案描述符洩漏。

注意記憶體。 compress() 與 decodeByteArray() 都是把整張圖放進記憶體,大圖容易觸發 OOM。若只是要縮圖,用 BitmapFactory.Options.inSampleSize 先降採樣,會比壓縮後再處理安全得多。

ARD_8888 與 RGB_565 的取捨。 上面用 getOpacity() 判斷是否透明來決定色彩配置,不透明的圖用 RGB_565 可省一半記憶體;需要保留 alpha 通道時才用 ARGB_8888。

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