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

Cách dùng Glide tải ảnh thành Bitmap trên Android

Giới thiệu

Glide (của BumpTech/Google) là thư viện tải ảnh/hệ thống media mạnh mẽ, hỗ trợ GIF, video thumbnail, lifecycle-aware. Bài viết hướng dẫn tải ảnh trực tiếp vào đối tượng Bitmap thay vì ImageView.

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

Bước 1: Tạo dự án và thêm dependency

Android Studio → File → New Project → Empty Activity.

Thêm vào build.gradle (Module: app):

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.16.0' // Phiên bản mới 2023
    annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
    // Phiên bản bài gốc: 4.9.0
}

Bước 2: 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"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

Bước 3: Logic (src/MainActivity.java)

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;

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

        imageView = findViewById(R.id.imageView);

        // Tải ảnh thành Bitmap
        Glide.with(this)
                .asBitmap() // Chỉ định loại resource mong muốn là Bitmap
                .load("https://www.google.es/images/srpr/logo11w.png")
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource,
                                                @Nullable Transition<? super Bitmap> transition) {
                        // Nhận được Bitmap, có thể dùng cho nhiều mục đích
                        imageView.setImageBitmap(resource);
                        // Hoặc: save to file, process, upload...
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // Được gọi khi request bị hủy hoặc View detach
                    }
                });
    }
}

Bước 4: Manifest

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

    <uses-permission android:name="android.permission.INTERNET" />

    <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. Ảnh Google logo tải về Bitmap và hiển thị.

Cách dùng Glide tải ảnh thành Bitmap trên Android

Các trường hợp dùng Bitmap thay vì ImageView

  • Xử lý ảnh: filter, crop, watermark, OCR, ML Kit
  • Lưu file cục bộ: bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
  • Chia sẻ qua Intent: intent.putExtra(Intent.EXTRA_STREAM, bitmapUri)
  • Upload multipart: convert Bitmap → byte[] → RequestBody
  • Hiển thị trong Notification (LargeIcon)

Các tùy chọn quan trọng của Glide

Glide.with(this)
    .asBitmap()
    .load(url)
    .apply(new RequestOptions()
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.error)
        .diskCacheStrategy(DiskCacheStrategy.ALL) // Cache cả original và transformed
        .override(800, 600) // Resize trước khi decode (tiết kiệm RAM)
        .format(DecodeFormat.PREFER_ARGB_8888) // Chất lượng cao
        .priority(Priority.HIGH)
    )
    .into(customTarget);

So sánh Target types

TargetDùng choLifecycle
ImageViewHiển thị trực tiếpTự động gắn với View lifecycle
CustomTarget<Bitmap>Lấy Bitmap objectPhải tự quản lý (clear trong onDestroy)
PreloadTargetPreload vào cacheKhông gắn View
NotificationTargetHiển thị trong NotificationTự quản lý
AppWidgetTargetWidget homescreenTự quản lý

Quản lý bộ nhớ với Bitmap

  • Luôn bitmap.recycle() khi không dùng nữa (API < 11) hoặc để GC tự dọn (API 11+)
  • Dùng inBitmap (BitmapFactory.Options) để tái sử dụng bộ nhớ
  • Glide tự quản lý pool Bitmap nội bộ (BitmapPool) - rất hiệu quả
  • Tránh load ảnh gốc kích thước lớn (4000x3000) vào Bitmap nhỏ - dùng .override()

Kotlin Coroutines Extension (Glide 4.12+)

// suspend function - dùng trong coroutine
val bitmap = Glide.with(this)
    .asBitmap()
    .load(url)
    .submit(width, height) // Trả về Deferred
    .await()