Conversion between Android-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. drawable → bitmap
Java code
  1. Public static bitmap drawabletobitmap (drawable ){
  2. Bitmap bitmap = bitmap
  3. . Createbitmap (
  4. Drawable. getintrinsicwidth (),
  5. Drawable. getintrinsicheight (),
  6. Drawable. getopacity ()! = Pixelformat. opaque? Bitmap. config. argb_8888
  7. : Bitmap. config. rgb_565 );
  8. Canvas canvas = new canvas (Bitmap );
  9. // Canvas. setbitmap (Bitmap );
  10. Drawable. setbounds (0, 0, drawable. getintrinsicwidth (), drawable. getintrinsicheight ());
  11. Drawable. Draw (canvas );
  12. Return bitmap;
  13. }

 
2. Obtain bitmap from a resource
 
Java code

  1. Resources res = getresources ();
  2. Bitmap BMP = bitmapfactory. decoderesource (Res, R. drawable. PIC );

 
3. Bitmap → byte []
 
Java code

  1. Private byte [] bitmap2bytes (Bitmap BM ){
  2. Bytearrayoutputstream baos = new bytearrayoutputstream ();
  3. BM. Compress (bitmap. compressformat. PNG, 100, baos );
  4. Return baos. tobytearray ();
  5. }

 
4. byte [] → bitmap
Java code

  1. Private bitmap bytes2bimap (byte [] B ){
  2. If (B. length! = 0 ){
  3. Return bitmapfactory. decodebytearray (B, 0, B. Length );
  4. }
  5. Else {
  6. Return NULL;
  7. }
  8. }

 
 
 
The above are some of the transformations I have encountered in practice. In the future, we don't need to look around for similar conversions. I hope they will be of some use to everyone!

Related Article

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.