Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

โหลดภาพด้วย Glide ใน Android


Glide คืออะไร?

Glide เป็น Library โหลดและแสดงภาพ (Image Loading Library) ที่ทรงพลัง พัฒนาโดย Bump Technologies ใช้งานง่าย รองรับการโหลดจาก URL, File, Resource, Assets รวมถึง GIF, Video Thumbnail และการ Transform รูปภาพ

ทำไมต้องใช้ Glide?

  • จัดการ Memory และ Disk Cache อัตโนมัติ
  • ป้องกัน OOM (OutOfMemoryError) ด้วย Downsampling
  • รองรับ Lifecycle (หยุดโหลดเมื่อ Fragment/Activity ถูก Destroy)
  • API เรียบง่าย Chainable (Fluent API)
  • รองรับ Placeholder, Error, Fallback, Transition

การติดตั้ง

build.gradle (Project) - ต้องมี Google Maven

allprojects {
    repositories {
        google()
        mavenCentral()
        // jcenter() // deprecated
    }
}

build.gradle (Module: app)

dependencies {
    // Glide core
    implementation 'com.github.bumptech.glide:glide:4.16.0'
    
    // Annotation Processor (จำเป็นสำหรับ Generated API)
    annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
    
    // สำหรับ Kotlin ใช้ ksp หรือ kapt
    // ksp 'com.github.bumptech.glide:compiler:4.16.0'
    // kapt 'com.github.bumptech.glide:compiler:4.16.0'
    
    // Optional: OkHttp integration (แนะนำ)
    implementation 'com.github.bumptech.glide:okhttp3-integration:4.16.0'
}

การใช้งานพื้นฐาน

Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

public class MainActivity extends AppCompatActivity {

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

        ImageView imageView = findViewById(R.id.imageView);

        // โหลดภาพพื้นฐาน
        Glide.with(this)
            .load("https://www.tutorialspoint.com/images/tp-logo-diamond.png")
            .into(imageView);
    }
}

คุณสมบัติขั้นสูง (Advanced Features)

1. Placeholder, Error, Fallback

Glide.with(this)
    .load(imageUrl)
    .placeholder(R.drawable.placeholder_image)      // ระหว่างโหลด
    .error(R.drawable.error_image)                  // โหลดล้มเหลว
    .fallback(R.drawable.fallback_image)            // URL เป็น null/empty
    .into(imageView);

2. Transformations (ปรับแต่งรูปภาพ)

import com.bumptech.glide.load.resource.bitmap.*;

// มุมโค้ง
RequestOptions options = new RequestOptions()
    .transform(new RoundedCorners(16)); // radius 16dp

// วงกลม (CircleCrop)
.transform(new CircleCrop())

// Blur
.transform(new BlurTransformation(25, 3))

// กรองสี (Grayscale)
.transform(new GrayscaleTransformation())

// ใช้ร่วมกัน
.transform(new MultiTransformation(
    new CenterCrop(), 
    new RoundedCorners(16)
))

3. Resize และ Scaling

// Override ขนาด (dp -> pixel ภายใน)
.override(300, 300)

// Scale Type
.centerCrop()      // เต็มพื้นที่ ตัดส่วนเกิน
.fitCenter()       // ใส่ทั้งรูป รักษาสัดส่วน
.centerInside()    // ใส่ทั้งรูป ถ้ารูปเล็กกว่าไม่ขยาย

// Downsampling (โหลดขนาดเล็กลงมาเพื่อประหยัด Memory)
.apply(new RequestOptions().downsample(DownsampleStrategy.AT_LEAST))

4. Disk Cache Strategy

.apply(new RequestOptions()
    .diskCacheStrategy(DiskCacheStrategy.ALL)      // Cache ทั้ง Original และ Transformed
    // .diskCacheStrategy(DiskCacheStrategy.DATA)   // Cache เฉพาะ Original
    // .diskCacheStrategy(DiskCacheStrategy.RESOURCE) // Cache เฉพาะ Transformed
    // .diskCacheStrategy(DiskCacheStrategy.NONE)   // ไม่ Cache
)

5. Listener และ Target

// Simple Target สำหรับ Bitmap
Glide.with(this)
    .asBitmap()
    .load(url)
    .into(new SimpleTarget() {
        @Override
        public void onResourceReady(@NonNull Bitmap resource, 
                                    @Nullable Transition transition) {
            // ใช้ Bitmap โดยตรง
            imageView.setImageBitmap(resource);
        }
    });

// Custom Target สำหรับ Notification, Widget, etc.
.into(new CustomTarget() {
    @Override
    public void onResourceReady(@NonNull Drawable resource, 
                                @Nullable Transition transition) { }

    @Override
    public void onLoadCleared(@Nullable Drawable placeholder) { }
});

6. GIF และ Video

// GIF - โหลดเป็น Drawable
Glide.with(this)
    .asGif()
    .load(gifUrl)
    .into(imageView);

// Video Thumbnail (ต้อง API 10+)
Glide.with(this)
    .load(videoUrl)
    .into(imageView); // Glide จะดึง Frame แรกอัตโนมัติ

7. Preload (โหลดล่วงหน้า)

// โหลดไว้ใน Cache ก่อนที่จะต้องแสดง
Glide.with(this)
    .load(url)
    .preload(); // หรือ .preload(width, height)

Glide Module (การกำหนดค่าส่วนกลาง)

สร้างคลาส implements AppGlideModule เพื่อตั้งค่า Global:

@GlideModule
public class MyAppGlideModule extends AppGlideModule {
    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        // ลงทะเบียน OkHttp
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
    }

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        // ตั้งค่า Cache size (bytes)
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, "glide_cache", 256 * 1024 * 1024)); // 256MB
    }

    @Override
    public boolean isManifestParsingEnabled() {
        return false; // ปิด Manifest parsing เพื่อ Build เร็วขึ้น
    }
}

Glide vs Picasso vs Coil

FeatureGlidePicassoCoil (Kotlin)
GIF/Video✅ รองรับดี❌ GIF เท่านั้น✅ รองรับ
Transformations✅ มากมาย✅ พื้นฐาน✅ มากมาย
Lifecycle Awareness✅ อัตโนมัติ❌ Manual✅ อัตโนมัติ
Kotlin Friendly✅ Extension⚠️ Java API✅ Native Kotlin
ขนาด Library~400KB~120KB~300KB

สรุป

  • Glide เป็นมาตรฐานอุตสาหกรรมสำหรับ Java/Kotlin Android
  • ใช้ Glide.with(context/fragment/view) เพื่อผูก Lifecycle อัตโนมัติ
  • ใช้ RequestOptions และ Transformation เพื่อปรับแต่ง
  • โปรเจกต์ Kotlin ใหม่ พิจารณา Coil ที่เขียนเป็น Kotlin Native