Drawable and Bitmap conversion, drawablebitmap
1. Bitmap to Drawable
Bitmap bm = xxx; // xxx is obtained based on your situation
BitmapDrawable bd = new BitmapDrawable (bm );
Because BtimapDrawable is a subclass of Drawable, you can directly use the bd object.
Ii. Conversion of Drawable to Bitmap
After being converted to a Bitmap object, the Drawable object can be converted into a byte output stream through the Android SK inventory, and finally saved as jpg and png files.
Drawable d = xxx; // xxx obtain drawable based on your own situation
BitmapDrawable bd = (BitmapDrawable) d;
Bitmap bm = bd. getBitmap ();
Finally, bm is the Bitmap object we need.
// Obtain Bitmap from the Resource
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 ();
}
// 1) Drawable → Bitmap
Public static Bitmap convertDrawable2BitmapByCanvas (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 );
// Canvas. setBitmap (bitmap );
Drawable. setBounds (0, 0, drawable. getIntrinsicWidth (),
Drawable. getIntrinsicHeight ());
Drawable. draw (canvas );
Return bitmap;
}
// 2) Drawable → Bitmap
Public static Bitmap convertDrawable2BitmapSimple (Drawable drawable ){
BitmapDrawable bd = (BitmapDrawable) drawable;
Return bd. getBitmap ();
}
// Bitmap → Drawable
Public static Drawable convertBitmap2Drawable (Bitmap bitmap ){
BitmapDrawable bd = new BitmapDrawable (bitmap );
// Because BtimapDrawable is a subclass of Drawable, you can directly use the bd object.
Return bd;
}
How does android convert bitmap to drawable?
Bitmap to Drawable:
Bitmap bitmap = new Bitmap (...);
Drawable drawable = new BitmapDrawable (bitmap );
This should be done
In android, how does one convert the image resources in Rdrawable to Bitmap?
Bitmap bmp = BitmapFactory. decodeResource (r, R. drawable. icon );
Bitmap newb = Bitmap. createBitmap (300,300, Config. ARGB_8888 );
Canvas canvasTemp = new Canvas (newb );
CanvasTemp. drawBitmap (bmp, 50, 50, p );