android在處理一寫圖片資源的時候,會進行一些類型的轉換,如今有空整理一下:android
一、Drawable → Bitmapcanvas
public static Bitmap drawableToBitmap(Drawable drawable) { code
Bitmap bitmap = Bitmap orm
.createBitmap( 圖片
drawable.getIntrinsicWidth(), ci
drawable.getIntrinsicHeight(), 資源
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 get
: Bitmap.Config.RGB_565); it
Canvas canvas = new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
二、從資源中獲取Bitmap
Resources res=getResources();
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
三、Bitmap → byte[]
private byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
四、 byte[] → Bitmap
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}