【问题标题】:Speed up image download time加快图像下载时间
【发布时间】: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 并且需要很长时间。这是为什么呢?

【问题讨论】:

标签: java android image performance


【解决方案1】:

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

【讨论】:

  • 知道这是怎么做到的吗?我以前没听说过这个,很高兴学习。
  • 这是对解决方案的高级描述。如果您将图像下载到客户端应用程序,您可能有一个带有 MVC 或类似架构服务器端(Ruby on Rails、Asp.NET 等)的服务器-客户端架构。您将在服务器上创建一个新操作,使用第三方库将图像放入 zip 文件中,将 zip 文件作为操作结果发送,然后使用客户端上的第三方库来解压缩图像。
【解决方案2】:

尝试将您的 InputStream 包装到 BufferedInputStream

BufferedInputStream bs = new BufferedInputStream(input);
Bitmap myBitmap = BitmapFactory.decodeStream(input);

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 1970-01-01
      • 2013-09-28
      • 2019-05-28
      • 2012-05-22
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多