Android開發實用技巧:Drawable和Bitmap之間不得不說的秘密

來源:互聯網
上載者:User

標籤:android   解決方案   

Bitmap - 稱作位元影像,一般位元影像的檔案格式尾碼為bmp,當然編碼器也有很多如RGB565、RGB888。作為一種逐像素的顯示對象執行效率高,但是缺點也很明顯儲存效率低。我們理解為一種儲存物件比較好。


Drawable - 作為Android平下通用的繪圖物件,它可以裝載常用格式的映像,比如GIF、PNG、JPG,當然也支援BMP,當然還提供一些進階的可視化對象,比如漸層、圖形等。
一. Bitmap轉Drawable
Bitmap bm = xxx; //xxx根據你的情況擷取

BitmapDrawable bd=new BitmapDrawable(bm);
因為BtimapDrawable是Drawable的子類,最終直接使用bd對象即可。

二. Drawable轉Bitmap
轉成Bitmap對象後,可以將Drawable對象通過Android的SK庫存成一個位元組輸出資料流,最終還可以儲存成為jpg和png的檔案。
Drawable d=xxx; //xxx根據自己的情況擷取drawable

BitmapDrawable bd = (BitmapDrawable) d;

Bitmap bm = bd.getBitmap();
最終bm就是我們需要的Bitmap對象了。

三. 從資源中擷取Bitmap
public static Bitmap getBitmapFromResources(Activity act, int resId) {
Resources res = act.getResources();
return BitmapFactory.decodeResource(res, resId);
}

四. byte[]轉Bitmap
public static Bitmap convertBytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.