Android 下载网络图片注意的问题

在使用的过程当中,若是网络比较慢的话,则会出现下载不成功的问题。通过google搜索,终于解决了这个问题。

  通常咱们会用如下的代码:

java代码:
//获取connection,方法略
conn = getURLConnection(url);
is = conn.getInputStream();java

//获取Bitmap的引用
Bitmap bitmap = BitmapFactory.decodeStream(is)数组


       可是网络很差的时候获取不了图片,推荐使用如下的方法:

java代码:
//获取长度
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;
}google

bitmap=BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}url


        使用上面的方法的好处是在网速很差的状况下也会将图片数据所有下载,而后在进行解码,生成图片对象的引用,因此能够保证只要图片存在均可如下载下来。固然在读取图片数据的时候也可用java.nio.ByteBuffer,这样在读取数据前就不用知道图片数据的长度也就是图片的大小了,避免了有时候 http获取的length不许确,而且不用作数组的copy工做。

java代码:
public synchronized Bitmap getBitMap(Context c, String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {code

myFileUrl = new URL(url);
} catch (MalformedURLException e) {
bitmap = BitmapFactory.decodeResource(c.getResources(),
com.jixuzou.moko.R.drawable.defaultimg);
return bitmap;
}orm

try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
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);
}
} catch (IOException e) {
bitmap = BitmapFactory.decodeResource(c.getResources(),com.jixuzou.moko.R.drawable.defaultimg);
return bitmap;
}
return bitmap;
}对象

相关文章
相关标签/搜索