1

在我的应用程序中,我正在下载从 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 并且需要很长时间。这是为什么?

4

3 回答 3

2

需要一段时间是完全自然的。对于您从 URL 加载的每个图像,都会发出一个新的 HTTP 请求(即向服务器发送一个请求并做出响应)。

那是网络上往返时间的 50 倍(甚至不包括服务器响应所需的时间)。检索图像后,您应该在本地缓存它们。

于 2013-10-24T16:15:46.630 回答
2

该过程中最长的步骤可能是向服务器发送请求并等待其响应,并且您将重复此步骤 50 次。你有能力修改服务器吗?如果是这样,请考虑添加一个操作,让您一次下载所有 50 个图像(可能通过将它们放入一个 zip 文件,然后在客户端解压缩它们)。

于 2013-10-24T16:36:35.603 回答
0

尝试将您的 InputStream 包装到 BufferedInputStream

BufferedInputStream bs = new BufferedInputStream(input);
Bitmap myBitmap = BitmapFactory.decodeStream(input);
于 2013-10-24T16:33:15.857 回答