Bitmap, Drawable, ByteArray 的交替使用

1 篇文章 / 0 new
author
Bitmap, Drawable, ByteArray 的交替使用
在圖形的使用上 Bitmap, Drawable, ByteArray 算是常用到的, 這之間的資料轉換方式如下

資料源 ByteArray -> Drawable -> Bitmap
ByteArrayInputStream bytes = new ByteArrayInputStream(byteImage);
BitmapDrawable bmd = new BitmapDrawable(bytes);
Bitmap bmp = bmd.getBitmap();

資料源 ByteArray -> Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(byteImage, 0, byteImage.length);

Drawable -> Bitmap
Drawable bmd = new BitmapDrawable(bmp);

Bitmap -> Pixel Array
int size = bmp.getRowBytes() * bmp.getHeight();
byte[] data = new byte[size];
ByteBuffer buf = ByteBuffer.wrap(data);//以 data 作儲存空間,轉入後可直接對 data 處理
//ByteBuffer buf = ByteBuffer.allocate(size);//若不是要對 pixel 資料作處理,可以直接配置空間
bmp.copyPixelsToBuffer(buf);//轉入 buffer
buf.rewind();
///從buffer轉出
bmp.copyPixelsFromBuffer(buf);
注意:轉出的 data 資料是不能給 BitmapFactory.decodeByteArray() 使用, 因為該 data資料僅pixel資料, 並不同於原始圖檔讀入 ByteArray內所包含的全部資訊

Bitmap儲存
public String saveBitmap(Bitmap bitmap, String dir, String baseName) {<br />
    try {<br />
        File sdcard = Environment.getExternalStorageDirectory();<br />
        File pictureDir = new File(sdcard, dir);<br />
        pictureDir.mkdirs();<br />
        File f = null;<br />
        for (int i = 1; i < 100; ++i) {<br />
            String name = baseName + i + ".png";<br />
            f = new File(pictureDir, name);<br />
            if (!f.exists()) { break; }<br />
        }<br />
        if (!f.exists()) {<br />
            String name = f.getAbsolutePath();<br />
            FileOutputStream fos = new FileOutputStream(name);<br />
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);<br />
            fos.flush();<br />
            fos.close();<br />
            return name;<br />
        }<br />
    } catch (Exception e) {<br />
    } finally {  }<br />
    return null;<br />
}
Free Web Hosting