android開發過成中時而需要BitMap 和Drable之間的轉換:
1. 網絡下載下傳圖檔轉換為Drawable代碼片段:
URL urlimage = new URL(imagepath);
URLConnection mConnection= urlimage.openConnection();
mConnection.connect(); //獲得連接配接
InputStream in=mConnection.getInputStream();
BitMap bitmap=BitmapFactory.decodeStream(in);
Drawable drawable = new BitmapDrawable(bitmap);
2.Drawable 轉化為 BitMap :
public static Bitmap drawableToBitmap(Drawable drawable)
{
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}