Conversion between drawable, bitmap, and byte)

Source: Internet
Author: User

Android will perform some type conversion when processing a write image resource. Now I have time to sort it out:

1. Simple Method of drawable → bitmap
(Bitmapdrawable) res. getdrawable (R. drawable. youricon). getbitmap ();

2. drawable → bitmap
Java Code
Public static bitmap drawabletobitmap (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;
}

3. Simple Method of Bitmap → drawable
Bitmapdrawable = (bitmapdrawable) bitmap;
Drawable = (drawable) bitmapdrawable;


Bitmap bitmap = new Bitmap (...);
Drawable = new bitmapdrawable (Bitmap );

3. Obtain bitmap from the Resource
Java code
Resources res = getresources ();

Bitmap BMP = bitmapfactory. decoderesource (Res, R. drawable. PIC );

4. Bitmap → byte []
Java code
Private byte [] bitmap2bytes (Bitmap BM ){
Bytearrayoutputstream baos = new bytearrayoutputstream (); & nbsp;
BM. Compress (bitmap. compressformat. PNG, 100, baos); & nbsp;
Return baos. tobytearray ();
}

5. byte [] → bitmap
JAVA code
private bitmap bytes2bimap (byte [] B) {
If (B. length! = 0) {
return bitmapfactory. decodebytearray (B, 0, B. length);
}< br> else {
return NULL;
}< BR >}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.