您的位置:首页 > 移动开发 > Android开发

Android中通过url获取图片Bitmap

2016-04-04 20:49 183 查看

Android中通过url获取图片Bitmap

这里直接上代码:

/**
* Author:FounderWatts
* context:调用方上下文,Activity.this
* urlStr:指定的网址,如:“http://www.baidu.com”
* */
public Bitmap getBitmapFromUrl(Context context,String urlStr){
URL url = null;
Bitmap bitmap = null;
HttpURLConnection connection = null;
try{
url = new URL(urlStr);
connection = (HttpURLConnection)url.openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);

InputStream inputStream = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();

}catch (Exception e){
e.printStackTrace();
Resources resources = context.getResources();
bitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher);
}finally {
connection.disconnect();
}
return bitmap;
}


注意到整个方法中没有声明 connection.connect(); 现在大部分的说法是在必要的情况下connect()方法会被隐式调用,不过我查看API源码,发现HttpURLConnection本身也是继承自URLConnection的抽象类,它并没有实现connect()抽象方法。至于具体connect()的调用情况我将尽快在我后面的博客给出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: