Bitmap, drawable, and byte [] conversion in Android advanced 2

Source: Internet
Author: User

Convert drawable to bitmap

Public static bitmap drawabletobitmap (drawable) {// obtain the length and width of drawable int W = drawable. getintrinsicwidth (); int H = drawable. getintrinsicheight (); // retrieves the drawable color format bitmap. config = drawable. getopacity ()! = Pixelformat. opaque? Bitmap. config. argb_8888: bitmap. config. rgb_565; // create the corresponding bitmapbitmap bitmap = bitmap. createbitmap (W, H, config); // create the canvas = new canvas (Bitmap); drawable. setbounds (0, 0, W, H); // draw the drawable content into the canvas. draw (canvas); Return bitmap ;}
Obtain bitmap from resources
Resources res = getResources();Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.icon);

Bitmap → byte []

public byte[] Bitmap2Bytes(Bitmap bm) {ByteArrayOutputStream baos = new ByteArrayOutputStream();bm.compress(Bitmap.CompressFormat.PNG, 100, baos);return baos.toByteArray();}

Byte [] → bitmap

public Bitmap Bytes2Bimap(byte[] b) {if (b.length != 0) {return BitmapFactory.decodeByteArray(b, 0, b.length);} else {return null;}}

Bitmap to drawable

Bitmap Bm = xxx; // XXX obtain bitmapdrawable BD = new bitmapdrawable (getresource (), BM) based on your situation. Because btimapdrawable is a subclass of drawable, you can directly use the BD object.

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.