我們的應用或多或少都會從網路擷取圖片資料然後進行顯示,下面就將實現一個這樣的例子,擷取網路中的圖片!
首先:我們來看一下
介面中有三個控制項,一個EditText,一個Button,一個ImageView
1、下面是具體布局檔案
<EditText
android:id="@+id/picturepagh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="查看" />
<ImageButton
android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="200px" />
2、在MainActivity中進行圖片圖示代碼編寫
public class MainActivity extends Activity {
private Button btn;
private EditText path;
private ImageView imgview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
path = (EditText) findViewById(R.id.picturepagh);
imgview = (ImageView) findViewById(R.id.imageView);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("CLICK", ((Button) v).getText().toString());
new Thread(runa).start();
}
});
}
public void setView() {
String picturepath = path.getText().toString();
byte[] data = null;
try {
data = ImageService.getImage(picturepath);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// BitmapFactory:圖片工廠!
Looper.prepare();// 必須調用此方法,要不然會報錯
Message msg = new Message();
msg.what = 0;
msg.obj = bitmap;
handler.sendMessage(msg);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "擷取圖片錯誤", 1).show();
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
updateImageView((Bitmap) msg.obj);
}
}
};
private Runnable runa = new Runnable() {
@Override
public void run() {
setView();
}
};
private void updateImageView(Bitmap bm) {
imgview.setImageBitmap(bm);
}
}
3、添加一個ImageService圖片服務類,裡麵包含一個擷取網路資料的方法;
public class ImageService {
// 擷取網狀圖片的資料
public static byte[] getImage(String picturepath) throws Exception {
URL url = new URL(picturepath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 基於http協議的連線物件
conn.setConnectTimeout(10);// 10秒;
conn.setRequestMethod("GET");// 大寫
if (conn.getResponseCode() == 200) {
InputStream ins = conn.getInputStream();
return StreamTool.read(ins);
}
return null;
}
}
4、添加一個流處理工作類StreamTool
public class StreamTool {
public static byte[] read(InputStream ins) throws Exception {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = ins.read(buffer)) > -1) {
outstream.write(buffer, 0, length);
}
outstream.close();
return outstream.toByteArray();
}
}
5、大功告成?NO,還要添加網路存取權限: <uses-permission android:name="android.permission.INTERNET" />
OK,運行程式!