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

Android 如何加載並顯示網絡圖片:從 URL 到 ImageView 的完整實戰

編輯:關於 Android 程式設計

很多初學 Android 的朋友都問過同一個問題:怎麼把網路上的圖片顯示到介面上?其實原理並不複雜,只要掌握「下載—轉流—解碼—顯示」這條主線即可。本文用一個完整範例,帶你走一遍從 URL 取得圖片、轉換成 Bitmap、最後呈現在 ImageView 裡的全流程。

整體思路是:先根據圖片網址建立連線,把網路資源讀成 InputStream 串流,再用 BitmapFactory 把串流解碼成 Bitmap 物件,而 Bitmap 正好可以直接塞進 ImageView 顯示。是不是比想像中簡單?跟著下面的步驟動手試試吧。

第一步,別忘了在 AndroidManifest.xml 裡加上網路訪問權限,否則程式根本連不上網:

<uses-permission android:name="android.permission.INTERNET" />

第二步,在佈局檔中放一個 ImageView 作為顯示容器:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" /> </LinearLayout> 

第三步,在主 Activity 中編寫下載與解碼的邏輯,把網路圖片變成能顯示的 Bitmap:

 package com.image; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.widget.ImageView; public class NetImageActivity extends Activity { /** Called when the activity is first created. */ String imageUrl = "https://content.52pk.com/files/100623/2230_102437_1_lit.jpg"; Bitmap bmImg; ImageView imView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imView = (ImageView) findViewById(R.id.imageView); imView.setImageBitmap(returnBitMap(imageUrl)); } public Bitmap returnBitMap(String url){ URL myFileUrl = null; Bitmap bitmap = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl .openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } } 

完成後執行程式,網路圖片就會顯示出來了。

運行效果:

小提醒:在較新的 Android 版本中,直接在主線程進行網路操作會拋出 NetworkOnMainThreadException,實務上建議把下載動作放到子執行緒或搭配非同步任務來處理。此外,關於 AndroidManifest.xml 的權限控制,也可以參考線上工具「Android Manifest 功能與權限描述大全」:
https://tools.jb51.net/table/AndroidManifest

以上就是本文的全部內容,希望對正在學習 Android 圖像處理的你有所幫助。

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