ভূমিকা
এই উদাহরণটি দেখাবে কিভাবে ড্রোয়েবল রিসোর্স থেকে একটি ছবি Bitmap-এ লোড করে ByteArrayOutputStream এবং Base64 এনকোডার ব্যবহার করে Base64 স্ট্রিং-এ রূপান্তর করতে হয়।
ধাপ ১: নতুন প্রজেক্ট তৈরি করুন
Android Studio-তে File → New Project নির্বাচন করুন।
ধাপ ২: লেআউট ফাইল (res/layout/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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:padding="4dp"/>
</RelativeLayout>
ধাপ ৩: ছবি যোগ করুন
আপনার প্রজেক্টের res/drawable/ ফোল্ডারে একটি ছবি রাখুন (উদাহরণ: logo.png)।
ধাপ ৪: মেইন এক্টিভিটি কোড (src/MainActivity.java)
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
TextView textView;
String string;
Bitmap bitmap;
@SuppressLint("WrongThread")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
string = Base64.encodeToString(bytes, Base64.DEFAULT);
textView.setText(string);
}
}
ধাপ ৫: মেনিফেস্ট ফাইল (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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
অ্যাপ্লিকেশন চালান
অ্যাপটি চালান। ড্রোয়েবল রিসোর্স থেকে ছবি লোড করে Base64 স্ট্রিং-এ রূপান্তরিত হয়ে TextView-এ দেখাবে।