Ví dụ này minh họa encode Bitmap thành Base64 string và decode ngược lại thành Bitmap bằng Kotlin.
Bước 1: Tạo dự án mới
Tạo dự án mới trong Android Studio, chọn Kotlin.
Bước 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Base64 <-> Bitmap chuyển đổi"
android:textColor="@android:color/holo_blue_dark"
android:textSize="16sp"
android:textStyle="bold|italic" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp" />
</LinearLayout>
Bước 3: MainActivity.kt
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import java.io.ByteArrayOutputStream
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView)
// 1. Bitmap -> ByteArray -> Base64 String
val baos = ByteArrayOutputStream()
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
val imageBytes: ByteArray = baos.toByteArray()
val imageString: String = Base64.encodeToString(imageBytes, Base64.DEFAULT)
// 2. Base64 String -> ByteArray -> Bitmap
val decodedBytes = Base64.decode(imageString, Base64.DEFAULT)
val decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
// Hiển thị
imageView.setImageBitmap(decodedBitmap)
}
}
Bước 4: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.q1">
<application ...>
<activity android:name=".MainActivity">...</activity>
</application>
</manifest>
Chạy ứng dụng
App load ảnh từ drawable, chuyển sang Base64, rồi decode ngược và hiển thị lên ImageView.