- How to convert a drawable to a bitmap in Android?
- Method 1: Using BitmapDrawable.getBitmap()
- Method 2: Using Bitmap.createBitmap()
- Method 3: Using Canvas.drawDrawable()
- How to convert Drawable to a Bitmap in Android?
- How to Convert a Drawable to a Bitmap
- How to load an image from drawable and convert to a bitmap
- How to create Bitmap form Drawable object
- Getting Bitmap from vector drawable
- converting drawable resource image into bitmap
- How to convert a Drawable to a scaled Bitmap
- How to convert a Bitmap to Drawable in android?
How to convert a drawable to a bitmap in Android?
In Android, a Drawable is a graphic element that can be drawn on a Canvas. It can be an image, a shape, or a combination of both. Sometimes, it is necessary to convert a Drawable to a Bitmap in order to manipulate its pixels or to save it as a file. In this article, we will present several methods to convert a Drawable to a Bitmap in Android.
Method 1: Using BitmapDrawable.getBitmap()
To convert a Drawable to a Bitmap in Android using BitmapDrawable.getBitmap() , you can follow these steps:
- First, create an instance of the BitmapDrawable class and pass the Drawable object that you want to convert as a parameter to its constructor.
- Then, call the getBitmap() method on the BitmapDrawable object to retrieve the converted Bitmap object.
- Finally, you can use the Bitmap object as needed in your application.
Here’s an example code snippet that demonstrates this process:
// Step 1: Create a BitmapDrawable object with the Drawable to convert BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.my_drawable); // Step 2: Convert the Drawable to a Bitmap using getBitmap() Bitmap bitmap = drawable.getBitmap(); // Step 3: Use the Bitmap as needed imageView.setImageBitmap(bitmap);
In this example, R.drawable.my_drawable is the ID of the Drawable resource that we want to convert. The imageView object is an instance of an ImageView that we want to set the converted Bitmap as its image.
Note that the getBitmap() method may throw a NullPointerException if the Drawable object is not a BitmapDrawable or if it has no intrinsic width or height. Therefore, you should always check for null before using the converted Bitmap object.
That’s it! This is how you can convert a Drawable to a Bitmap in Android using BitmapDrawable.getBitmap() .
Method 2: Using Bitmap.createBitmap()
To convert a Drawable to a Bitmap in Android using Bitmap.createBitmap() , follow these steps:
- Get the intrinsic width and height of the Drawable object using drawable.getIntrinsicWidth() and drawable.getIntrinsicHeight() methods.
- Create a Bitmap object using Bitmap.createBitmap() method with the intrinsic width and height of the Drawable object.
- Create a Canvas object with the Bitmap object using new Canvas(bitmap) constructor.
- Draw the Drawable object on the Canvas object using drawable.draw(canvas) method.
Here is an example code snippet that demonstrates the above steps:
Drawable drawable = getResources().getDrawable(R.drawable.my_drawable); int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas);
In the above code, R.drawable.my_drawable is the ID of the Drawable resource that you want to convert to a Bitmap. Bitmap.Config.ARGB_8888 is the Bitmap configuration that specifies the pixel format. You can change it to other configurations based on your requirements.
This method is useful when you want to manipulate the Bitmap object further, such as applying filters or transformations.
Method 3: Using Canvas.drawDrawable()
To convert a Drawable to a Bitmap using Canvas.drawDrawable() , follow these steps:
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);
// Use the Bitmap imageView.setImageBitmap(bitmap);
// Get the Drawable from resources Drawable drawable = getResources().getDrawable(R.drawable.my_drawable); // Create a Bitmap object with the same dimensions as the Drawable Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); // Create a Canvas object with the Bitmap Canvas canvas = new Canvas(bitmap); // Draw the Drawable onto the Canvas drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); // Use the Bitmap imageView.setImageBitmap(bitmap);
Note: This method is not recommended for large or complex Drawables, as it may cause performance issues. It is recommended to use other methods, such as BitmapFactory.decodeResource() , for those cases.
How to convert Drawable to a Bitmap in Android?
This example demonstrates how do I convert Drawable to a Bitmap in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity; 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; public class MainActivity extends AppCompatActivity < ImageView imageView; Button btnConvert; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); btnConvert = findViewById(R.id.btnConvert); btnConvert.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); imageView.setImageBitmap(bitmap); Toast.makeText(getApplicationContext(), "Image converted to Bitmap", Toast.LENGTH_SHORT).show(); >>); > >
Step 4 − Add the following code to androidManifest.xml
Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
How to Convert a Drawable to a Bitmap
How to load an image from drawable and convert to a bitmap
The following method should work fine:
public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) drawable = (DrawableCompat.wrap(drawable)).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;
>
dependencies classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
>
android compileSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig minSdkVersion 16
targetSdkVersion 23
vectorDrawables.useSupportLibrary = true
>
.
>
.
Or, you can use android-ktx in Kotlin too like this which works for any subclass of Drawable :
dependencies implementation 'androidx.core:core-ktx:1.0.0-alpha1'
>
Then use Drawable#toBitmap() like this:
val bitmap = AppCompatResources.getDrawable(requireContext(), drawableId).toBitmap()
How to create Bitmap form Drawable object
You can convert your Drawable to Bitmap like this (for resource):
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.drawable_source);
If you’ve it stored in a variable, you can use this :
public static Bitmap drawableToBitmap (Drawable drawable) Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) return bitmapDrawable.getBitmap();
>
>
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
> else 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;
>
Getting Bitmap from vector drawable
public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) Drawable drawable = ContextCompat.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) drawable = (DrawableCompat.wrap(drawable)).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;
>
dependencies classpath 'com.android.tools.build:gradle:2.2.0-alpha5'
>
android compileSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig minSdkVersion 16
targetSdkVersion 23
vectorDrawables.useSupportLibrary = true
>
.
>
.
converting drawable resource image into bitmap
You probably mean Notification.Builder.setLargeIcon(Bitmap) , right? 🙂
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);
This is a great method of converting resource images into Android Bitmap s.
How to convert a Drawable to a scaled Bitmap
With pskink’s answer (Make Image view rounded (not the image)) to a similar question I came to the following solution, based on the saveLayer approach (with some minor modifications).
@Override
public void onDraw( Canvas canvas )
Paint paint1 = new Paint( Paint.ANTI_ALIAS_FLAG )
Paint paint2 = new Paint()
paint2.setXfermode( new PorterDuffXfermode( Mode.SRC_IN ) )
Drawable drawable = getDrawable()
RectF rectangle = new RectF()
rectangle.set( drawable.getBounds() )
getImageMatrix.mapRect( rectangle )
rectangle.offset( getPaddingLeft(), getPaddingTop() )
// Prevent radius being drawn out of canvas bounds
rectangle.intersect( new RectF( 0, 0, canvas.getWidth(), canvas.getHeight() ) )
int restore = canvas.saveLayer( rectangle, null, Canvas.ALL_SAVE_FLAG )
canvas.drawRoundRect( rectangle, radius.getValue(), radius.getValue(), paint1 )
canvas.saveLayer( rectangle, paint2, Canvas.ALL_SAVE_FLAG )
super.onDraw( canvas )
canvas.restoreToCount( restore )
>
The above code ignores object caching in class level and ignores NPE from getDrawable().
How to convert a Bitmap to Drawable in android?
Sounds like you want to use BitmapDrawable
A Drawable that wraps a bitmap and can
be tiled, stretched, or aligned. You
can create a BitmapDrawable from a
file path, an input stream, through
XML inflation, or from a Bitmap
object.