專案中若無需引入 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());
}
BitmapFactory.Options.inSampleSize 進行縮放解碼,避免 OOM。LruCache 做記憶體快取;複雜專案請直接接入 Glide / Coil / Picasso,自動處理生命週期、快取、佔位圖、轉換等。res/xml/network_security_config.xml 設定 cleartextTrafficPermitted="true" 或全面遷移 HTTPS。