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

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

      一、初始化信息

//定义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;

}


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


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值