android通过url获取bitmap,Android从URL加载到Bitmap

我喜欢这些:

从InputStream创建Bitmap并返回它:

public static  Bitmap downloadImage(String url) {

Bitmap bitmap = null;

InputStream stream = null;

BitmapFactory.Options bmOptions = new BitmapFactory.Options();

bmOptions.inSampleSize = 1;

try {

stream = getHttpConnection(url);

bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);

stream.close();

}

catch (IOException e1) {

e1.printStackTrace();

System.out.println("downloadImage"+ e1.toString());

}

return bitmap;

}

// Makes HttpURLConnection and returns InputStream

public static  InputStream getHttpConnection(String urlString)  throws IOException {

InputStream stream = null;

URL url = new URL(urlString);

URLConnection connection = url.openConnection();

try {

HttpURLConnection httpConnection = (HttpURLConnection) connection;

httpConnection.setRequestMethod("GET");

httpConnection.connect();

if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

stream = httpConnection.getInputStream();

}

}

catch (Exception ex) {

ex.printStackTrace();

System.out.println("downloadImage" + ex.toString());

}

return stream;

}

请记住:

Android包括两个HTTP客户端:HttpURLConnection和Apache HTTP Client。 对于姜饼和后来,HttpURLConnection是最好的选择。

从Android 3.x Honeycomb或更高版本,您无法在UI线程上执行网络IO并执行此操作会抛出android.os.NetworkOnMainThreadException。您必须使用Asynctask,如下所示

/**     AsyncTAsk for Image Bitmap  */

private class AsyncGettingBitmapFromUrl extends AsyncTask {

@Override

protected Bitmap doInBackground(String... params) {

System.out.println("doInBackground");

Bitmap bitmap = null;

bitmap = AppMethods.downloadImage(params[0]);

return bitmap;

}

@Override

protected void onPostExecute(Bitmap bitmap) {

System.out.println("bitmap" + bitmap);

}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值