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

วิธีโหลดรูปภาพลง ImageView จาก URL ด้วย Picasso ใน Android

การโหลดรูปภาพจากอินเทอร์เน็ตแสดงใน ImageView ด้วย Library Picasso

ตัวอย่างนี้แสดงวิธีใช้ Library Picasso (Square) เพื่อดาวน์โหลดและแสดงรูปภาพจาก URL ลงใน ImageView แบบ Asynchronous พร้อม Caching อัตโนมัติ

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → กรอกรายละเอียด → Finish

ขั้นตอนที่ 2: เพิ่ม Dependency ใน build.gradle (Module: app)

dependencies {
    // ... dependencies อื่นๆ
    implementation 'com.squareup.picasso:picasso:2.71828' // เวอร์ชันล่าสุด
}

คลิก "Sync Now" หลังเพิ่ม

ขั้นตอนที่ 3: Layout - res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="โหลดรูปภาพจาก URL"
        android:textStyle="bold"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp" />
    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="16dp"
        android:scaleType="centerCrop" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp"
        android:gravity="center|bottom"
        android:textStyle="bold" />
</LinearLayout>

ขั้นตอนที่ 4: MainActivity.java

package app.com.sample;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;

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

        imageView = findViewById(R.id.image_view);
        String url = "https://images.pexels.com/photos/814499/pexels-photo-814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
        
        // โหลดรูปด้วย Picasso - หนึ่งบรรทัด!
        Picasso.get()
            .load(url)
            .placeholder(R.drawable.placeholder) // รูปขณะโหลด (optional)
            .error(R.drawable.error_image)       // รูปเมื่อโหลดล้มเหลว (optional)
            .into(imageView);
    }
}

ขั้นตอนที่ 5: AndroidManifest.xml

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

คุณสมบัติหลักของ Picasso

Methodคำอธิบาย
load(url/file/resource)ระบุแหล่งที่มารูปภาพ
placeholder(resId)รูปช่วงกำลังโหลด
error(resId)รูปเมื่อโหลดล้มเหลว
fit()ปรับขนาด ImageView ให้พอดีกับรูป
centerCrop() / centerInside()การปรับ Scale Type
resize(w, h)Resize รูปภาพ (ไม่เกี่ยวกับ View)
rotate(degrees)หมุนรูปภาพ
transform(Transformation)Custom Transformation (Circle, Blur, etc.)
priority(Priority)HIGH/LOW/IMMEDIATE
noFade()ปิด Animation Fade-in
into(imageView)เริ่มโหลดและตั้งค่าให้ ImageView

Callback สำหรับตรวจสอบสถานะ

Picasso.get().load(url).into(imageView, new Callback() {
    @Override
    public void onSuccess() {
        Log.d("Picasso", "โหลดสำเร็จ");
    }
    @Override
    public void onError(Exception e) {
        Log.e("Picasso", "โหลดล้มเหลว", e);
    }
});

// หรือใช้ Target สำหรับกรณีไม่ได้ set ให้ ImageView โดยตรง
Target target = new Target() {
    @Override public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) { }
    @Override public void onBitmapFailed(Exception e, Drawable errorDrawable) { }
    @Override public void onPrepareLoad(Drawable placeholder) { }
};

Picasso vs Glide vs Coil

Libraryขนาดคุณสมบัติเด่น
Picasso~100KBSimple API, Auto-caching, Reliable
Glide~400KBGIF/Video, Lifecycle integration, Customizable
Coil~500KBKotlin-first, Coroutines, Compose support

⚠️ ข้อควรระวัง

  • ต้องเพิ่ม INTERNET Permission
  • Picasso 2.71828+ ใช้ Picasso.get() แทน Picasso.with(context) (Deprecated)
  • สำหรับ RecyclerView/ListView ให้ใช้ Picasso.get().load(url).into(holder.imageView) โดยตรง
  • Clear cache: Picasso.get().cache.clear()