Bitmap ↔ Drawable কনভার্সন: BitmapDrawable ব্যবহার
এই উদাহরণে দেখানো হয়েছে কিভাবে একটি Drawable-কে Bitmap-এ এবং আবার Bitmap-কে Drawable-এ (BitmapDrawable) রূপান্তর করা যায়। বাটন ক্লিক করলে রিসোর্স থেকে Drawable নিয়ে Bitmap বানানো হয়, তারপর আবার Drawable বানানো হয়।
ধাপ ১: প্রজেক্ট তৈরি করুন
Android Studio-তে নতুন প্রজেক্ট শুরু করুন।
ধাপ ২: লেআউট (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Bitmap ↔ Drawable কনভার্ট করুন" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnConvert"
android:layout_marginTop="10dp" />
</RelativeLayout>
ধাপ ৩: MainActivity.java
package com.example.sample;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
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(v -> {
// ১. রিসোর্স থেকে Drawable পান
Drawable drawable = getResources().getDrawable(R.drawable.your_image, getTheme());
// ২. Drawable → Bitmap (BitmapDrawable কাস্ট করে)
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// ৩. Bitmap → Drawable (BitmapDrawable কনস্ট্রাক্টর)
Drawable newDrawable = new BitmapDrawable(getResources(), bitmap);
// ৪. ImageView-এ সেট করুন
imageView.setImageDrawable(newDrawable);
});
}
}
প্রধান মেথডসমূহ
| রূপান্তর | কোড |
|---|---|
| Drawable → Bitmap | ((BitmapDrawable) drawable).getBitmap() |
| Bitmap → Drawable | new BitmapDrawable(resources, bitmap) |
| VectorDrawable → Bitmap | Canvas-এ draw করে Bitmap.createBitmap() |
মনে রাখবেন
- শুধু
BitmapDrawableকাস্ট করা যায়, অন্য Drawable (Vector, Shape, Ripple) কাস্ট করলে ClassCastException হবে। - VectorDrawable কে Bitmap বানাতে
Bitmap.createBitmap()+Canvasব্যবহার করুন। - মেমরি ম্যানেজমেন্ট: বড় Bitmap recycle করুন যদি আর লাগে না।
ফলাফল
"কনভার্ট করুন" বাটনে ট্যাপ করলে ড্রয়েবল রিসোর্স Bitmap-এ বদলে আবার Drawable-এ রূপান্তরিত হয়ে ImageView-এ দেখাবে।