Android में Drawable से Bitmap कन्वर्जन का तरीका
यह उदाहरण दिखाता है कि ड्रॉएबल रिसोर्स (जैसे @drawable/image) को Bitmap ऑब्जेक्ट में कैसे बदला जाता है ताकि इमेज प्रोसेसिंग या मैनिपुलेशन की जा सके।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project चुनें।
चरण 2: लेआउट फ़ाइल (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:padding="4dp"
android:gravity="center"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnConvert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Convert Drawable to Bitmap" />
</LinearLayout>
चरण 3: 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(v -> {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
imageView.setImageBitmap(bitmap);
Toast.makeText(getApplicationContext(), "Image converted to Bitmap", Toast.LENGTH_SHORT).show();
});
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
अन्य उपयोगी तरीके
- VectorDrawable से Bitmap:
Bitmap.createBitmap()औरCanvasउपयोग करें। - ImageView से Bitmap:
imageView.getDrawable()लेकर फिर कन्वर्ट करें। - बड़ी इमेज के लिए
inSampleSizeके साथBitmapFactory.Optionsउपयोग करें ताकि OOM एरर न हो।