標籤: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();
}