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

Android 如何從伺服器下載並顯示圖片

編輯:關於 Android 程式設計

在 Android 應用中,從伺服器抓取圖片並顯示於畫面是很常見的需求。以下範例示範如何以 HttpGet 向伺服器請求圖片,透過串流解碼為 Bitmap,再設定到 ImageView 上。

從伺服器取得 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();

        pic = BitmapFactory.decodeStream(is); // 關鍵:將串流解碼為 Bitmap

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

其中 imagePath 是你的圖片網址。整個流程重點在於:先以 HTTP 請求取得回應,從中取出資料串流,最後以 BitmapFactory.decodeStream() 將串流解碼成 Bitmap 物件。

將圖片顯示於畫面

取得 Bitmap 後,即可透過 setImageBitmap() 把它顯示在 ImageView 上:

imageView.setImageBitmap(bitmap);

提醒:由於網路請求屬於耗時操作,實務上應將下載動作放在背景執行緒(如 AsyncTask 或 Thread)中進行,避免阻塞主 UI 執行緒導致應用無回應。

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