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

วิธีดาวน์โหลดรูปภาพจาก URL ใน Android

การดาวน์โหลดรูปภาพจากอินเทอร์เน็ตด้วย AsyncTask และ BitmapFactory

ตัวอย่างนี้แสดงวิธีดาวน์โหลดรูปภาพจาก URL ใน Background Thread ด้วย AsyncTask แล้วนำ Bitmap มาแสดงใน ImageView พร้อม ProgressDialog

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

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

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

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/image"
        android:layout_centerHorizontal="true"
        android:text="@string/button" />
</RelativeLayout>

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

package app.com.sample;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    String url = "https://images.pexels.com/photos/1226302/pexels-photo-1226302.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
    ImageView image;
    Button button;
    ProgressDialog progressDialog;

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

        image = findViewById(R.id.image);
        button = findViewById(R.id.button);

        button.setOnClickListener(v -> new DownloadImage().execute(url));
    }

    private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("ดาวน์โหลดรูปภาพ");
            progressDialog.setMessage("กำลังโหลด...");
            progressDialog.setIndeterminate(false);
            progressDialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            String imageURL = urls[0];
            Bitmap bitmap = null;
            try {
                InputStream input = new java.net.URL(imageURL).openStream();
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                image.setImageBitmap(result);
            }
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    }
}

ขั้นตอนที่ 4: String Resource - res/values/strings.xml

<resources>
    <string name="app_name">Sample</string>
    <string name="menu_settings">Settings</string>
    <string name="button">ดาวน์โหลดรูปภาพ</string>
</resources>

ขั้นตอนที่ 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>

⚠️ หมายเหตุ: AsyncTask ถูก Deprecated แล้ว (API 30)

Google แนะนำให้ใช้ทางเลือกอื่นแทน:

1. Coroutines + Coil/Picasso/Glide (แนะนำ)

// ใช้ Library โหลดรูป (ไม่ต้องเขียน AsyncTask เอง)
implementation 'io.coil-kt:coil:2.4.0'
// หรือ
implementation 'com.squareup.picasso:picasso:2.71828'

// ใน Coroutine
lifecycleScope.launch {
    val bitmap = coilImageLoader.execute(ImageRequest.Builder(context).data(url).build()).drawable.bitmap
    imageView.setImageBitmap(bitmap)
}

2. ExecutorService / Thread Pool

ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(() -> {
    Bitmap bitmap = downloadImage(url);
    handler.post(() -> {
        imageView.setImageBitmap(bitmap);
        progressDialog.dismiss();
    });
});

3. Kotlin Coroutines (Modern)

// build.gradle: implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.0'
lifecycleScope.launch(Dispatchers.IO) {
    val bitmap = withContext(Dispatchers.IO) { downloadImage(url) }
    withContext(Dispatchers.Main) {
        imageView.setImageBitmap(bitmap)
        progressDialog.dismiss()
    }
}

4. WorkManager (สำหรับ Background Download ที่ต้อง Survive Process Death)

// เหมาะสำหรับดาวน์โหลดไฟล์ใหญ่ ที่ต้องทำงานต่อแม้แอปจะถูกปิด

การจัดการ Bitmap ให้มีประสิทธิภาพ

// Decode ด้วย inSampleSize เพื่อลดหน่วยความจำ
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // ลดขนาดลง 1/2
options.inPreferredConfig = Bitmap.Config.RGB_565; // ใช้หน่วยความจำน้อยกว่า ARGB_8888
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);

การทดสอบ

รันแอปบนอุปกรณ์จริง (ต้องมีอินเทอร์เน็ต) → กดปุ่ม "ดาวน์โหลดรูปภาพ" → แสดง ProgressDialog → โหลดเสร็จแสดงรูปใน ImageView