Java tutorial
//package com.java2s; //License from project: Open Source License import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.ByteArrayOutputStream; public class Main { /** * Create a byte array out of drawable * * @param drawable The source drawable * @return The byte array of source drawable */ public static byte[] getByteArrayFromDrawable(Drawable drawable) { if (drawable == null) { return null; } Bitmap bitmap = getBitmapFromDrawable(drawable); if (bitmap == null) { return null; } ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); } /** * Extract an underlying bitmap from a drawable * * @param sourceDrawable The source drawable * @return The underlying bitmap */ public static Bitmap getBitmapFromDrawable(Drawable sourceDrawable) { if (sourceDrawable == null) { return null; } if (sourceDrawable instanceof BitmapDrawable) { return ((BitmapDrawable) sourceDrawable).getBitmap(); } else { //copying drawable object to not manipulate on the same reference Drawable.ConstantState constantState = sourceDrawable.getConstantState(); if (constantState == null) { return null; } Drawable drawable = constantState.newDrawable().mutate(); Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } } }