android中在网络中取图片

在做android开发的时候,经常需要从网上下载一些图片,在界面上显示,一般的获取图片都会使用如下的代码:

1 //获取connection,方法略
2  conn = getURLConnection(url);
3 is = conn.getInputStream();
4  //获取Bitmap的引用
5  Bitmap bitmap = BitmapFactory.decodeStream(is)
//获取connection,方法略conn = getURLConnection(url);is = conn.getInputStream();//获取Bitmap的引用Bitmap bitmap = BitmapFactory.decodeStream(is)

但是上面的方法在设备上或是网速不太好的情况下,会获取不了图片,推荐使用如下的方法:

//获取长度int length = (int) conn.getContentLength();if (length != -1) {byte[] imgData = new byte[length];byte[] temp=new byte[512];int readLen=0;int destPos=0;while((readLen=is.read(temp))>0){System.arraycopy(temp, 0, imgData, destPos, readLen);destPos+=readLen;}bitmap=BitmapFactory.decodeByteArray(imgData, 0, imgData.length);}

 使用上面的方法的好处是在网速不好的情况下也会将图片数据全部下载,然后在进行解码,生成图片对象的引用,所以可以保证只要图片存在都可以下载下来。当然在读取图片数据的时候也可用java.nio.ByteBuffer,这样在读取数据前就不用知道图片数据的长度也就是图片的大小了,避免了有时候http获取的length不准确,并且不用做数组的copy工作。

原文地址:https://www.cnblogs.com/enricozhang/p/1743745.html