Conversion between Android drawable, bitmap, and byte []

Source: Internet
Author: User

1. drawable --> bitmap

    Bitmap drawable2Bitmap(Drawable drawable) {        if (drawable instanceof BitmapDrawable) {            return ((BitmapDrawable) drawable).getBitmap();        } else if (drawable instanceof NinePatchDrawable) {            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);            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),                    drawable.getIntrinsicHeight());            drawable.draw(canvas);            return bitmap;        } else {            return null;        }    }

2. The drawable --> bitmap obtained from the Resource

    Resources res = getResources();    Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);

3. Bitmap --> drawable

    Drawable bitmap2Drawable(Bitmap bitmap) {        return new BitmapDrawable(bitmap);    }

4. Bitmap --> byte []

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

5. byte [] --> bitmap

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

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.