在我的应用程序中,我正在下载从 URL 获取的图像。这里的问题是它花费的时间太长了。图片经过压缩,只有 9 公里大。我正在下载其中的 50 个,所以假设应用程序正在下载 500kByte 的图像。这应该很快吧?好吧,事实并非如此。有时我会等待 20 秒,直到加载完毕。什么在那里花了这么长时间?我有一个非常简单的方法来下载图像。在这里
int downloadingImages = getDownloadImageCount();
System.out.println(downloadingImages);
if(downloadingImages == 0){
for(int c = downloadingImages; c < 50; c++){
try{
bitmapArr[c] = getBitmapFromURL(imageURLArr[c]);
setDownloadImageCount(50);
publishProgress(c);
} catch (FileNotFoundException f1){
Log.v("FileNotFoundException", "Bitmap konnte nicht geladen werden");
} catch(NullPointerException e){
} catch (IllegalStateException ie){
}
setDownloadImageCount(50);
}
}
这是 getBitmapFromUrl 函数
public static Bitmap getBitmapFromURL(String src) throws FileNotFoundException {
try {
//Downloading the image
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
try{
//Saving the image to a bitmap and return it
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
//Catch Exception if file not found
} catch(FileNotFoundException ffe){
Log.v("FileNotFoundException", "getBitmapFromURLMethod");
return null;
}
//Catch Exception if error at input and output
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
我的意思是,为什么要花这么长时间?我怎样才能提高速度。稍后我将对图像使用缓存,但仍然......我的意思是它是 500kbs 并且需要很长时间。这是为什么?
最佳答案
这需要一段时间是完全自然的。对于您从 URL 加载的每个图像,都会发出一个新的 HTTP 请求(即向服务器发送请求并作出响应)。
这是网络往返时间的 50 倍(甚至不包括服务器响应可能花费的时间)。检索到图像后,您应该在本地缓存图像。
关于java - 加快图像下载时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19570558/