Android Drawable和Bitmap的轉(zhuǎn)換實例詳解
通常我們需要通過代碼去設(shè)置圖片,就需要設(shè)置圖片Bitmap和Drawable的轉(zhuǎn)換,下面整理了幾種方式
一、Bitmap轉(zhuǎn)Drawable
Bitmap bm=xxx; //xxx根據(jù)你的情況獲取 BitmapDrawable bd=new BitmapDrawable(bm);//因為BtimapDrawable是Drawable的子類,最終直接使用bd對象即可。
二、 Drawable轉(zhuǎn)Bitmap
Drawable d=xxx; //xxx根據(jù)自己的情況獲取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(); }
只是很簡單代碼片段,還是很容易懂得