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

本文来自:安卓航班网

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

  一般我们会用以下的代码:

java代码:

//获取connection,方法略
conn = getURLConnection(url);
is
= conn.getInputStream();
//获取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;
}
bitmap
=BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
}

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

java代码:

public synchronized Bitmap getBitMap(Context c, String url) {
URL myFileUrl
= null;
Bitmap bitmap
= null;
try {
myFileUrl
= new URL(url);
}
catch (MalformedURLException e) {
bitmap
= BitmapFactory.decodeResource(c.getResources(),
com.jixuzou.moko.R.drawable.defaultimg);
return bitmap;
}
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;
}

原文地址:http://www.apkway.com/forum.php?mod=viewthread&tid=2747&extra=page%3D1

转载于:https://www.cnblogs.com/yyq-quan/archive/2011/08/14/2138406.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值