Image Convert to Bitmap, ByteArray, Drawable in Android or Android studio

Sometimes we stocked during image processing in android in to ImageView, if will be be through exception.

Here is the some image convert in to bitmap and reverse process.

Convert Drawable image in to bitmap:

Bitmap profimeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile);

Another methods, if above not working

public Bitmap convertToBitmap(Drawable profile, int widthPixels, int heightPixels) {
     Bitmap profileBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(profileBitmap);
    profile.setBounds(0, 0, widthPixels, heightPixels);

    return profileBitmap;

Getting Bitmap from image url

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        return null;

Convert Bitmap type image to Drawable,

Drawable drawableProfile = new BitmapDrawable(getResources(), bitmapProfile);

Covert Bitmap to BitmapDrawable

BitmapDrawable bdProfile= new BitmapDrawable(bitmapProfile);

Retrive Bitmap when you set bitmap image on imageview,


Now, getting bitmap from imageView ,

Bitmap bitmapProfile = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

Convert from bitmap to byte array:

public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();

Convert SD Card Image to Bitmap to Byte Array:

String path="/path/images/image.jpg";

public byte[] getBytesFromBitmap(String path) {
    Bitmap bitmap = BitmapFactory.decodeFile(path);
   ByteArrayOutputStream blob = new ByteArrayOutputStream();
   bitmap.compress(CompressFormat.PNG, 0 , blob);
   byte[] bitmapdata = blob.toByteArray();
   return bitmapdata;

Convert from byte array to bitmap:

Bitmap bitmapProfile = BitmapFactory.decodeByteArray(bitmapbyteArraydata , 0, bitmapbyteArraydata .length);


public Bitmap ByteArrayToBitmap(byte[] byteArray)
        ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(byteArray);
        Bitmap bitmapProfile = BitmapFactory.decodeStream(arrayInputStream);
        return bitmapProfile;

Image Convert to Bitmap, ByteArray, Drawable in Android or Android studio Image Convert to Bitmap, ByteArray, Drawable  in Android or Android studio   Reviewed by D Kshetri on 11:36 AM Rating: 5

No comments:

Powered by Blogger.