1. 首先需要即將加載的圖片的地址
private static final String PATH = "http://h.hiphotos.baidu.com/image/w3D2048/sign=2766611cbe315c6043956cefb989ca13/c83d70cf3bc79f3d3f442939b8a1cd11728b2916.jpg";
2. 利用圖片地址打開網絡連接:
URL url = new URL(PATH); // 定義URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 打開連接
InputStream input = conn.getInputStream(); // 取得輸入流
3.定義字節數組,用輸入流向裏面輸入數據,同時定義輸出流,用來將數據輸出到內存當中
byte data[] = new byte[1024]; // 每次讀取1024
while ((len = input.read(data)) != -1) { // 沒有讀取到底部
bos.write(data, 0, len); // 向內存中保存
}
代碼:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
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 MyWebDemo extends Activity {
private static final String PATH = "http://h.hiphotos.baidu.com/image/w%3D2048/sign=2766611cbe315c6043956cefb989ca13/c83d70cf3bc79f3d3f442939b8a1cd11728b2916.jpg";
private ImageView img = null; // 定義圖片顯示
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main); // 調用佈局管理器
this.img = (ImageView) super.findViewById(R.id.img); // 取得組件
try {
byte data[] = this.getUrlData(); // 接收數據
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); // 生成圖形
this.img.setImageBitmap(bm); // 顯示圖片
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] getUrlData() throws Exception { // 取得網絡圖片數據
ByteArrayOutputStream bos = null; // 內存輸出流
try {
bos = new ByteArrayOutputStream(); // 定義內存輸出流
URL url = new URL(PATH); // 定義URL
byte data[] = new byte[1024]; // 每次讀取1024
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 打開連接
InputStream input = conn.getInputStream(); // 取得輸入流
int len = 0; // 接收讀取長度
while ((len = input.read(data)) != -1) { // 沒有讀取到底部
bos.write(data, 0, len); // 向內存中保存
}
return bos.toByteArray(); // 將內存中的數組變爲字節數組返回
} catch (Exception e) {
throw e;
} finally {
if (bos != null) {
bos.close(); // 關閉輸出流
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>