根据url下载网络图片

public void download(final Context context, final String url) {
new Thread(new Runnable() {


@Override
public void run() {
//下载图片
Bitmap bitmap = getImageFromNet(url);


// ivIcon.setImageBitmap(bitmap); // 设置imageView显示的图片
if (bitmap != null) {


Message msg = new Message();
msg.what = SUCCESS;
msg.obj = bitmap;
handler.sendMessage(msg);


System.out.println("下载成功");
Looper.prepare();
Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
Looper.loop();
} else {
System.out.println("下载失败");
Looper.prepare();
Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
}).start();
}

/**

* 根据url连接取网络抓去图片返回

* @param url
* @return url对应的图片
*/
private Bitmap getImageFromNet(String url) {
HttpURLConnection conn = null;
try {
URL mURL = new URL(url); // 创建一个url对象


// 得到http的连接对象
conn = (HttpURLConnection) mURL.openConnection();


conn.setRequestMethod("GET"); // 设置请求方法为Get
conn.setConnectTimeout(10000); // 设置连接服务器的超时时间, 如果超过10秒钟, 没有连接成功, //
// 会抛异常
conn.setReadTimeout(10000); // 设置读取数据时超时时间, 如果超过5秒, 抛异常
conn.setDoInput(true);


conn.connect(); // 开始链接
int responseCode = conn.getResponseCode(); // 得到服务器的响应码


if (responseCode == 200) {

InputStream is = conn.getInputStream(); // 获得服务器返回的流数据
if (is != null)
Log.e(TAG, "is is not null" + is.toString());


/**
* 第一种方法去解析图片
*/
// 将流转换成字节
byte[] data = readStream(is);
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
return bitmap;
}
/**
* 第二种方法解析图片
*/
// Bitmap bitmap = BitmapFactory.decodeStream(is); // 根据 流数据
// return bitmap;


} else {
System.out.println(responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect(); // 断开连接
}
}
return null;
}


/**
* 得到图片字节流 数组大小

* @param inStream
* @return
* @throws Exception
*/
public  byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值