技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機純凈版,64位旗艦版,綠色軟件,免費軟件下載基地!

當前位置:主頁 > 教程 > 服務(wù)器類 >

Android Drawable和Bitmap的轉(zhuǎn)換實例教程

來源:技術(shù)員聯(lián)盟┆發(fā)布時間:2017-10-28 18:23┆點擊:

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

只是很簡單代碼片段,還是很容易懂得