📌  相关文章
📜  getcokor from drawable in java android studio - Java (1)

📅  最后修改于: 2023-12-03 14:41:23.633000             🧑  作者: Mango

Get Bitmap from Drawable in Java Android Studio

In this tutorial we will show you how to get Bitmap from Drawable in Java Android Studio.

Introduction

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.

Steps
Step 1: Create a project in Android Studio

Create a new project in Android Studio named "GetBitmapFromDrawableExample".

Step 2: Add Drawable Image to Resources

Add an image to drawable folder of your project.

Step 3: Add ImageView to Layout

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" />
Step 4: Load Drawable Image to ImageView

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);
    }
}
Step 5: Converting Drawable to Bitmap

Now, we will convert the Drawable Object to Bitmap Object:

Drawable drawable = getResources().getDrawable(R.drawable.image);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
Step 6: Display Bitmap

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);
Conclusion

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.