Android开发技术之──获取网络图片

来源:互联网 发布:apache系列番号公司的 编辑:程序博客网 时间:2024/06/05 12:18

      在开发中,经常需要从服务端获取资源信息,下面我将获取网络图片的步骤及代码展示给大家:

      一、初始化信息

//定义ImageView对象

ImageView imgView;

 public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        /*

         * (若使用代理上网)解决android模拟器,不能上网的问题

         * 1.通知Java您要通过代理进行连接

         * 2.指定代理所在的服务器

         * 3.指定代理监听的端口

         */

        System.getProperties().put("proxySet", "true");

        System.getProperties().put("proxyHost","192.168.121.32");

        System.getProperties().put("proxyPort", "8080");

        

        setContentView(R.layout.main);

        

        //通过findViewById获得ImageView对象

imgView = (ImageView)findViewById(R.id.image_view);

        //显示图片

        showImage();

}

    二、发送图片请求

//显示图片方法

private void showImage() {

    imgView.setImageBitmap(null);

String urlpath = "http://image3.xxxxxxx.cn/content/catentries/00000000010136/000000000101360962/fullimage/000000000101360962_1f.png";  

   

        //根据要下载的图片的地址,获得图片Bitmap信息

    Bitmap bitmap = getHttpBitmap(urlpath);

        //将得到的Bitmap赋给imgView对象

    imgView.setImageBitmap(bitmap);    

}

    /*

     * 从服务器取图片

     * http://image3.xxxxxx.cn/content/catentries/00000000010136/000000000101360962/fullimage/000000000101360962_1f.png

     * 参数:String类型

     * 返回:Bitmap类型

     */

    public static Bitmap getHttpBitmap(String urlpath) {

    Bitmap bitmap = null;

try {

//生成一个URL对象

URL url = new URL(urlpath);

//打开连接

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

//conn.setConnectTimeout(6*1000);

//conn.setDoInput(true);

conn.connect();

//得到数据流

InputStream inputstream = conn.getInputStream();

Log.i("MyTag", "******************InputStream:"+inputstream+"******************");

bitmap = BitmapFactory.decodeStream(inputstream);

//关闭输入流

inputstream.close();

//关闭连接

conn.disconnect();

} catch (Exception e) {

// TODO: handle exception

Log.i("MyTag", "******************************************");

Log.i("MyTag", "error:"+e.toString());

}

Log.i("Debug", "bitmap:"+bitmap);

return bitmap;

}


    经过以上步骤,我们将网络上的图片信息展示到前端!


原创粉丝点击