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

Chuyển đổi hình ảnh thành chuỗi Base64 trên Android

Giới thiệu

Bài viết này trình bày cách chuyển đổi một hình ảnh (Bitmap) thành chuỗi Base64 trên Android. Điều này hữu ích khi cần truyền hình ảnh qua mạng, lưu vào database hoặc chia sẻ qua JSON/XML.

Các bước thực hiện

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 (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"
    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:textStyle="bold" />

</RelativeLayout>

Bước 3: Viết code chuyển đổi (src/MainActivity.java)

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

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @SuppressLint("WrongThread")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);

        // 1. Đọc hình ảnh từ drawable
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.instaimage);

        // 2. Nén bitmap thành mảng byte
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] imageBytes = byteArrayOutputStream.toByteArray();

        // 3. Encode thành Base64
        String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        // 4. Hiển thị kết quả
        textView.setText(imageString);
    }
}

Bước 4: Cấu hình Manifest (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>

Chạy ứng dụng

Kết nối thiết bị Android, nhấn Run trong Android Studio, chọn thiết bị và quan sát kết quả hiển thị chuỗi Base64 trên màn hình.

Lưu ý quan trọng

  • Đảm bảo có file hình ảnh instaimage trong thư mục res/drawable/.
  • Annotation @SuppressLint("WrongThread") chỉ dùng cho demo. Trong thực tế, nên xử lý nén ảnh trên background thread (Coroutine, RxJava, ExecutorService) để tránh block UI thread.
  • Base64 làm tăng dung lượng dữ liệu khoảng 33% so với binary gốc.
  • Để decode ngược lại: Base64.decode(imageString, Base64.DEFAULT) → BitmapFactory.decodeByteArray().