关于将网络上的图片下载保存到本地的效率对比

Android里面将图片保存到本地,到网络上搜索了一下,方法都差不多,大同小异,把输入流转换成输出流的过程而已。最近工作闲,特把其中的两个方法对比一下,看他们的效率如何(找javaSE里面测试的):

[b]第一种方法:[/b]
public static void main(String[] args) {

String url = "http://pic.yesky.com/imagelist/09/01/11277904_7147.jpg";

Long time1 = System.currentTimeMillis();
Long time2 = 0L;

try {
FileOutputStream fos = new FileOutputStream( "c:\\tmp.jpg ");
InputStream is = new URL(url).openStream();

time2 = System.currentTimeMillis();

int data = is.read();
while(data!=-1){
fos.write(data);
data=is.read();
}
is.close();
fos.close();

} catch (IOException e) {

e.printStackTrace();
}


Long time3 = System.currentTimeMillis();
System.out.println("网络读取流的时间:" + (time2 - time1) + " 把输入流保存成文件的时间:"+ (time3 - time2));

}


[b]第二种方法:中间用buffer做缓存[/b]
public static void main(String[] args){

String url = "http://pic.yesky.com/imagelist/09/01/11277904_7147.jpg";

Long time1 = System.currentTimeMillis();
Long time2 = 0L;

try {
int bytesum=0;
int byteread=0;
FileOutputStream fos = new FileOutputStream( "c:\\tmp2.jpg ");
InputStream is = new URL(url).openStream();

time2 = System.currentTimeMillis();

byte[] buffer =new byte[4096];
while ((byteread=is.read(buffer))!=-1)
{
bytesum+=byteread;
// System.out.println(bytesum);
fos.write(buffer,0,byteread);
}
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}

Long time3 = System.currentTimeMillis();
System.out.println("网络读取流的时间:" + (time2 - time1) + " 把输入流保存成文件的时间:"+ (time3 - time2));

}


每个方法测试了三次,结果如下:
第一种方法:
网络读取流的时间:453 把输入流保存成文件的时间:766
网络读取流的时间:344 把输入流保存成文件的时间:344
网络读取流的时间:297 把输入流保存成文件的时间:281

第二种方法:
网络读取流的时间:312 把输入流保存成文件的时间:282
网络读取流的时间:3484 把输入流保存成文件的时间:906
网络读取流的时间:828 把输入流保存成文件的时间:1250

第一种方法,发现效率高过第二种方法,而且第一种方法写法简洁的多。[b][color=red]建议用第一种方法[/color][/b]。
其实在android里面,不建议直接把网络图片原样写人sd里面,毕竟手机的sd空间是有限的。最常用的方法是把网络图片压缩成jpg格式保存:
byte[] data = readInputStream(new URL(url).openStream());
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);

bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(
file));


readInputStream()方法的代码:(把输入流转换成比特流)
public static byte[] readInputStream(InputStream inStream) throws Exception{  
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = 0;
while( (len = inStream.read(buffer)) != -1 ){
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值