【发布时间】:2013-11-03 10:24:14
【问题描述】:
在我的应用程序中,我正在下载从 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;
}
}
我的意思是,什么需要这么长时间?我怎样才能提高速度。稍后我将使用cahin 来处理图像,但仍然......我的意思是它是500kbs 并且需要很长时间。这是为什么呢?
【问题讨论】:
-
不要试图重新发明轮子:square.github.io/picasso
-
把一个时间戳作为一个长的多行。这可以告诉你什么时间太长了。与服务器连接也是一个耗时的过程。因此,请确保建立连接需要时间或下载。
-
你也可以使用通用图片加载器:github.com/nostra13/Android-Universal-Image-Loader
标签: java android image performance