萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 從網路獲取圖片的輕量級工具方法

專案中若無需引入 Glide/Picasso 等大型圖片庫,僅需簡單同步下載單張圖片並轉為 Bitmap,可使用以下封裝良好的靜態方法。支援 HTTP/HTTPS、自動檢查回應碼、異常轉換為統一拋出,適合在背景執行緒中呼叫。

核心工具方法

public class ImageDownloader {

    /**
     * 同步下載網路圖片並解碼為 Bitmap
     * @param urlString 圖片完整 URL
     * @return 解碼後的 Bitmap,失敗拋出 Exception
     * @throws Exception 網路錯誤、非 200 回應、解碼失敗等
     */
    public static Bitmap getImage(String urlString) throws Exception {
        try {
            URL url = new URL(urlString);
            // 檢查 HTTP 回應碼
            String responseCode = url.openConnection().getHeaderField(0); // HTTP/1.1 200 OK
            if (responseCode == null || responseCode.indexOf("200") < 0) {
                throw new Exception("圖片不存在或路徑錯誤,回應碼:" + responseCode);
            }
            // 直接解碼輸入流
            return BitmapFactory.decodeStream(url.openStream());
        } catch (IOException e) {
            throw new Exception("網路異常:" + e.getMessage());
        }
    }
}

呼叫範例(必須在背景執行緒)

// 使用 Thread + Handler 或 AsyncTask / Coroutines
new Thread(() -> {
    try {
        runOnUiThread(() -> showLoading("正在載入圖片..."));
        final Bitmap bitmap = ImageDownloader.getImage("https://example.com/avatar.jpg");
        runOnUiThread(() -> {
            hideLoading();
            imageView.setImageBitmap(bitmap);
        });
    } catch (Exception e) {
        runOnUiThread(() -> {
            hideLoading();
            showError(e.getMessage());
        });
    }
}).start();

進階補充:加入連線逾時與快取

public static Bitmap getImage(String urlString, int connectTimeoutMs, int readTimeoutMs) throws Exception {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(connectTimeoutMs);
    conn.setReadTimeout(readTimeoutMs);
    conn.setRequestMethod("GET");
    conn.setInstanceFollowRedirects(true);

    int responseCode = conn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new Exception("HTTP 錯誤:" + responseCode);
    }
    return BitmapFactory.decodeStream(conn.getInputStream());
}

最佳實踐提醒

  • 嚴禁在主執行緒呼叫:會導致 ANR(Application Not Responding)。
  • 大圖處理: 使用 BitmapFactory.Options.inSampleSize 進行縮放解碼,避免 OOM。
  • 快取策略: 簡單專案可用 LruCache 做記憶體快取;複雜專案請直接接入 Glide / Coil / Picasso,自動處理生命週期、快取、佔位圖、轉換等。
  • 網路安全配置: Android 9 (API 28) 預設禁用明文 HTTP,需在 res/xml/network_security_config.xml 設定 cleartextTrafficPermitted="true" 或全面遷移 HTTPS。
copyright © 萬盛學電腦網 all rights reserved