Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Chuyển đổi hình ảnh thành Base64 String Android Kotlin

Hướng dẫn này minh họa cách chuyển đổi hình ảnh (Image) thành chuỗi Base64 String trên Android sử dụng Kotlin.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (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"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:textSize="12sp"
        android:textColor="@android:color/background_dark"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Viết code MainActivity.kt

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.ByteArrayOutputStream

class MainActivity : AppCompatActivity() {
    lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        textView = findViewById(R.id.textView)

        val byteArrayOutputStream = ByteArrayOutputStream()
        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream)
        val imageBytes: ByteArray = byteArrayOutputStream.toByteArray()
        val imageString: String = Base64.encodeToString(imageBytes, Base64.DEFAULT)
        textView.text = imageString
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.q11">

    <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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. TextView sẽ hiển thị chuỗi Base64 dài đại diện cho hình ảnh R.drawable.image.

Giải thích quy trình

  1. BitmapFactory.decodeResource() - Đọc drawable thành Bitmap
  2. bitmap.compress(JPEG, 100, stream) - Nén bitmap thành byte array (quality 100%)
  3. Base64.encodeToString(bytes, DEFAULT) - Encode byte array thành Base64 string

Decode Base64 ngược lại thành Bitmap

fun base64ToBitmap(base64String: String): Bitmap? {
    return try {
        val decodedBytes = Base64.decode(base64String, Base64.DEFAULT)
        BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

Ứng dụng thực tế

  • Gửi hình ảnh qua API JSON (REST)
  • Lưu ảnh vào SharedPreferences/Database dạng text
  • Embed ảnh vào HTML/CSS (data URI): data:image/jpeg;base64,...
  • Chuyển ảnh giữa các platform (Android ↔ iOS ↔ Web)

Lưu ý hiệu năng

  • Base64 tăng kích thước ~33% so với binary
  • Không dùng cho ảnh lớn (>1MB) trên main thread
  • Cân nhắc compress WEBP quality 80% thay vì JPEG 100%
  • Xử lý trên background thread (Coroutines/RxJava) cho ảnh lớn

Extension function tiện lợi

fun Bitmap.toBase64(format: Bitmap.CompressFormat = Bitmap.CompressFormat.WEBP, quality: Int = 80): String {
    val outputStream = ByteArrayOutputStream()
    compress(format, quality, outputStream)
    return Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP)
}

fun String.toBitmap(): Bitmap? = Base64.decode(this, Base64.DEFAULT)
    .let { BitmapFactory.decodeByteArray(it, 0, it.size) }