android 如何获取并显示WEB服务器的图片

发布时间:2011年07月21日      浏览次数:387 次
本文主要描述android 如何获取并显示网络上的图片,代码经测试通过。
------------------------------------------------------------------------
Test_Img_List.java 代码如下:
------------------------------------------------------------------------
package com.android.MySoft;

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 Test_Img_List extends Activity {
      String imageUrl = "http://www.baidu.com/img/baidu_sylogo1.gif";
      Bitmap bmImg;
      ImageView imView;

      /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_img_list);

setTitle("测试获取网络图片");

imView = (ImageView) findViewById(R.id.imageView1);
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;
}
}

------------------------------------------------------------------------
test_img_list.xml 代码如下:
------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView1"></ImageView>
</LinearLayout>
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!