📅  最后修改于: 2023-12-03 14:41:23.633000             🧑  作者: Mango
In this tutorial we will show you how to get Bitmap from Drawable in Java Android Studio.
Sometimes we may need to get the Bitmap from Drawable in Android. This can be useful if we want to use the Bitmap for any processing or store it in cache or disk. In this tutorial, we will learn how to load the Drawable and convert it into Bitmap.
Create a new project in Android Studio named "GetBitmapFromDrawableExample".
Add an image to drawable folder of your project.
Add an ImageView to activity_main.xml file:
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
Load the image from drawable folder to the ImageView by using setImageDrawable() method in MainActivity.java file.
package com.example.getbitmapfromdrawableexample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.drawable.Drawable;
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);
// Get the ImageView
ImageView imageView = findViewById(R.id.image_view);
// Load drawable image to imageView
Drawable drawable = getResources().getDrawable(R.drawable.image);
imageView.setImageDrawable(drawable);
}
}
Now, we will convert the Drawable Object to Bitmap Object:
Drawable drawable = getResources().getDrawable(R.drawable.image);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
Then, we can display this Bitmap in another ImageView. Add another ImageView to the Layout and display the Bitmap.
<ImageView
android:id="@+id/image_view_bitmap"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
// Get the ImageView
ImageView imageViewBitmap = findViewById(R.id.image_view_bitmap);
// Convert Drawable to Bitmap
Drawable drawable = getResources().getDrawable(R.drawable.image);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
// Set Bitmap to ImageView
imageViewBitmap.setImageBitmap(bitmap);
In this tutorial, we have learned how to load the Drawable and convert it into a Bitmap. We have also displayed this Bitmap to another ImageView. With this knowledge, you can use the Bitmap for further processing, such as saving it in cache or disk, or sending it over a network.