How to Convert Drawable to a Bitmap in Android

In this android programming example code, we are going to illustrate how to convert drawable to bitmap in android.

Image drawable is stored in the drawable folder inside the res folder.

We will use the code below to convert a drawable to a bitmap and display it on an ImageView.

Steps

  1. Add an ImageView and a Button in xml layout file
  2. Get the instances of the ImageView and Button Views
  3. Attach event click listener to the button view
  4. When the button is clicked, create a bitmap from an image drawable usingĀ BitmapFactory.decodeResource(getResources(), R.drawable.camera)method.
  5. Display the bitmap on ImageView

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <Button
        android:layout_marginTop="120dp"
        android:id="@+id/convertToBitmap"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:text="Convert to Bitmap"
        android:padding="12dp"
        android:textColor="@color/colorWhite"
        android:background="@color/colorAccent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView imageView = findViewById(R.id.imageView2);
        Button drawable2Bitmap = findViewById(R.id.convertToBitmap);

        drawable2Bitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.camera);
                imageView.setImageBitmap(bitmap);
                Toast.makeText(getApplicationContext(), "Image converted to Bitmap", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

android convert to bitmap

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment