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

Cách truyền hình ảnh (Image) giữa 2 Activity trong Android

Giới thiệu

Bài viết này hướng dẫn cách truyền hình ảnh từ Activity này sang Activity khác trong Android. Có 3 cách chính: truyền Resource ID, truyền Bitmap, hoặc truyền đường dẫn file/URI.

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

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

Khởi tạo project Android Studio mới.

Bước 2: Layout Activity chính (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="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnSendImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:onClick="sendImage"
        android:text="Gửi hình ảnh sang Activity 2" />

    <ImageView
        android:id="@+id/ivSourceImage"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/btnSendImage"
        android:layout_marginTop="10dp"
        android:scaleType="centerCrop"
        android:src="@drawable/sample_image" />

</RelativeLayout>

Bước 3: MainActivity - Gửi Resource ID (src/MainActivity.java)

package app.com.sample;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

    public void sendImage(View view) {
        // Cách 1: Truyền Resource ID (NHẸ NHÀNH, KHUYẾN NGHỊ cho drawable trong app)
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("imageResId", R.drawable.sample_image);
        startActivity(intent);

        // Cách 2: Truyền Bitmap (chỉ cho ảnh nhỏ, < 1MB - tránh TransactionTooLargeException)
        // Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_image);
        // intent.putExtra("bitmap", bitmap); // Parcelable

        // Cách 3: Truyền URI file (cho ảnh từ gallery, camera, file storage)
        // Uri imageUri = ...; intent.putExtra("imageUri", imageUri.toString());
    }
}

Bước 4: Layout Activity 2 (res/layout/activity_second.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=".SecondActivity">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Activity Nhận Hình Ảnh"
        android:textSize="24sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/ivReceivedImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tvTitle"
        android:layout_marginTop="5dp"
        android:scaleType="centerCrop" />

</RelativeLayout>

Bước 5: SecondActivity - Nhận và hiển thị (src/SecondActivity.java)

package app.com.sample;

import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

    ImageView ivReceivedImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        ivReceivedImage = findViewById(R.id.ivReceivedImage);

        // Nhận dữ liệu từ Intent
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // Cách 1: Nhận Resource ID
            int resId = extras.getInt("imageResId", -1);
            if (resId != -1) {
                ivReceivedImage.setImageResource(resId);
                return;
            }

            // Cách 2: Nhận Bitmap
            // Bitmap bitmap = extras.getParcelable("bitmap");
            // if (bitmap != null) ivReceivedImage.setImageBitmap(bitmap);

            // Cách 3: Nhận URI
            // String uriString = extras.getString("imageUri");
            // if (uriString != null) {
            //     ivReceivedImage.setImageURI(Uri.parse(uriString));
            // }
        }
    }
}

Bước 6: Manifest (Đăng ký 2 Activity)

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

        <activity android:name=".SecondActivity" />

    </application>
</manifest>

Chạy ứng dụng

Chạy app, nhấn nút "Gửi hình ảnh sang Activity 2". Activity 2 mở ra và hiển thị cùng hình ảnh.

Cách truyền hình ảnh (Image) giữa 2 Activity trong Android

So sánh 3 cách truyền hình ảnh

Best Practice cho ảnh lớn (Glide/Picasso/Coil)

// MainActivity
intent.putExtra("imageUrl", "https://example.com/large-image.jpg");
// Hoặc file path
intent.putExtra("imagePath", "/storage/emulated/0/Pictures/photo.jpg");

// SecondActivity - dùng thư viện load ảnh
Glide.with(this).load(getIntent().getStringExtra("imageUrl")).into(ivReceivedImage);
// Hoặc Coil (Kotlin)
imageView.load(getIntent().getStringExtra("imageUrl"))

Lưu ý quan trọng

  • KHÔNG truyền Bitmap lớn qua Intent (crash: TransactionTooLargeException)
  • Dùng putExtra("key", value) cho primitive/String, putParcelable() cho Bitmap/Uri
  • Luôn check extras != null và default value khi getInt()
  • Để chia sẻ ảnh với app khác: dùng Intent.ACTION_SEND với setType("image/*")
CáchƯu điểmNhược điểmPhù hợp
Resource ID (int)Nhẹ, nhanh, không giới hạn kích thướcChỉ dùng cho drawable trong appIcon, ảnh assets, drawable XML
Bitmap (Parcelable)Truyền bitmap đã xử lýGiới hạn ~1MB (Binder limit), tốn bộ nhớẢnh nhỏ, thumbnail, ảnh đã edit
URI (File/Content)Hỗ trợ ảnh lớn, từ storage/gallery/cameraCần quyền đọc file, xử lý content resolverẢnh từ camera, gallery, download