1

I started to build a game, this game gets images from server.

I used Bitmap to convert the IMAGE*S* and its works slowly.

Its take 25 - 40 seconds to load 22 images (100KB for each image).


public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

Implementation:


Bitmap pictureBitmap = ImageFromUrl.getBitmapFromURL(path);

PS..

I used LazyList before ,and it's not for my goal.

More offers?

Tnx....

4

1 回答 1

1

您在解码时尝试getInputStream()从 HTTP 连接使用BitmatpFactory,因此BitmatpFactory工厂总是必须等待输入流来收集数据。

而且我没有看到任何close()输入流 - 期待锡finally块,这可能会导致进一步的错误。

尝试这个:

  • 在单独的线程中创建 HTTP 连接,以便您可以同时下载图像。

  • 仅在文件下载后解码位图(您可能必须为位图解码器打开另一个流,但它比您当前的解决方案更快、更清晰)。

让我们还检查您的连接带宽,以确保您所做的事情受到此因素(网络带宽)的限制。

[更新] 这些是一些实用功能:

/**
 * Util to download data from an Url and save into a file
 * @param url
 * @param outFilePath
 */
public static void HttpDownloadFromUrl(final String url, final String outFilePath)
{
    try
    {
        HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        FileOutputStream outFile = new FileOutputStream(outFilePath, false);
        InputStream in = connection.getInputStream();

        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0)
        {
            outFile.write(buffer, 0, len);
        }
        outFile.close();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

/**
 * Spawn a thread to download from an url and save into a file
 * @param url
 * @param outFilePath
 * @return
 *      The created thread, which is already started. may use to control the downloading thread.
 */
public static Thread HttpDownloadThreadStart(final String url, final String outFilePath)
{
    Thread clientThread = new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            HttpDownloadFromUrl(url, outFilePath);
        }
    });
    clientThread.start();

    return clientThread;
}
于 2013-04-03T04:22:30.863 回答