android 获取网络图片方法 常见错误以及解决办法


private Bitmap getUrlimg(String url) throws IOException {
Bitmap bitmap = null;
URL imageUrl = null;
String head = "http://114.80.209.134:13080/";
String tureUrl = head + url;
imageUrl = new URL(tureUrl);

HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bitmap =
bis.close();
is.close();

return bitmap;
}

以前经常用这种方式获得图片,但是今天发现当图片比较多而且大时,经常 失败,

后来发现 io流的获取没有出错,得到的是完整的io流,但是 还是失败,发现是那个 BitmapFactory.decodeStream(bis);的问题 后来改成这样,见下,可以完全解决问题。

private Bitmap getUrlimg(String url) throws IOException {
Bitmap bitmap = null;
URL imageUrl = null;
String head = "http://114.80.209.134:13080/";
String tureUrl = head + url;
imageUrl = new URL(tureUrl);

HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.connect();
InputStream is = conn.getInputStream();
byte[] bt = getBytes(is);
bitmap = BitmapFactory.decodeByteArray(bt, 0, bt.length);
is.close();
conn.disconnect();
return bitmap;
}

private byte[] getBytes(InputStream is) throws IOException {

ByteArrayOutputStream baos =new ByteArrayOutputStream();

byte[] b =new byte[1024];
int len = 0;
while ((len = is.read(b, 0, 1024)) !=-1) {
baos.write(b, 0, len);
baos.flush();
}
byte[] bytes = baos.toByteArray();
return bytes;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值