Convert a Drawable to a Bitmap in Android-Java

thumbnail

In this tutorial you will learn to convert a Drawable to a Bitmap using Java. First, you need to add new drawable (You can choose any image you want). Then, make sure you have activity_main.xml and main_activity.java.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Convert a Drawable to Bitmap in Android"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="center"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/iv_image"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"
        app:layout_constraintTop_toBottomOf="@id/tv_title"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

main_activity.java

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView bitmapImage = (ImageView) findViewById(R.id.iv_image);
        Bitmap bitmapImageLocal = BitmapFactory.decodeResource(
                getApplicationContext().getResources(),
                R.drawable.jetpack_logo);
        bitmapImage.setImageBitmap(bitmapImageLocal);
    }
}

When you run the app, the ouput will be:

Convert a Drawable to a Bitmap in Android-Java
Convert a Drawable to a Bitmap in Android-Java
Back To Top