您的位置:首页 > 其它

如何从服务器获取图片

2014-05-08 22:16 183 查看
今天写了安卓程序与服务器通信,其中需要从服务器获取图片。本来以为下载流、处理文件流很复杂,结果几句话就轻松搞定了。现在记在这里。
// (2014.5.1第一种方法)通过服务器返回的图片url,再次向服务器请求,添加动态新闻图片
// 读取Bitmap图片
try {
Bitmap bm;
URL url;
url = new URL(map.get("activityPhoto").toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
// 加载到布局文件中
newsImage = (ImageView) findViewById(R.id.imageView);
newsImage.setImageBitmap(bm);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
主要过程是先通过Ajax请求到服务器的图片路径(不是想象中的图片流,服务器只会返回请求的图片资源的路径,而后由客户端根据url再次访问),然后根据url再次建立连接,请求图片流,并解码解析,生成图片。关联相关的布局文件中的控件,通过setImageBitmap()函数设置资源id即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: