Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 從服務器下載並顯示圖片的實現方法

編輯:關於 Android 程式設計

核心只有一句:BitmapFactory.decodeStream()。把網絡流直接交給它解碼,就能拿到 Bitmap 對象。

public static Bitmap getBitmapFromServer(String imagePath) {

    HttpGet get = new HttpGet(imagePath);
    HttpClient client = new DefaultHttpClient();
    Bitmap pic = null;
    try {
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        // 關鍵:直接把流交給 BitmapFactory 解碼
        pic = BitmapFactory.decodeStream(is);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return pic;
}

其中 imagePath 是圖片在服務器上的完整地址。

顯示到界面上

imageView.setImageBitmap(bitmap);

實務上要注意的幾點

1. 網絡請求不能放在 UI 線程。Android 4.0 之後拋 NetworkOnMainThreadException,需配合線程、AsyncTask 或 Handler 使用。

2. InputStream 用完要關閉,建議用 try-with-resources 或 finally 顯式關流,否則容易洩露連接。

3. 大圖直接 decodeStream 極易 OOM。實用做法是先用 BitmapFactory.Options 的 inJustDecodeBounds 讀取尺寸,再按目標顯示大小計算 inSampleSize 做降採樣。

4. 高頻加載場景(如列表縮略圖)應引入內存緩存與磁盤緩存,避免反覆網絡請求。

5. 上述 HttpClient / DefaultHttpClient 已在較新版本 Android 中被標記為廢棄,新項目建議改用 HttpURLConnection 或 OkHttp。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved