2013-04-03 80 views
1

我开始构建一款游戏,这款游戏从服务器获取图片。图片来自URL

我用位图转换图像* S *及其作品缓慢。

及其采取25 - 40秒的负载22倍的图像(100KB为每个图像)。


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; 
    } 
} 

实现:


Bitmap pictureBitmap = ImageFromUrl.getBitmapFromURL(path); 

PS ..

我之前使用LazyList,这不是我的目标。

更多供应信息?

TNX ....

+0

你可以参考这个链接http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-网址功能于安卓 –

回答

1

您是从HTTP连接,同时其使用BitmatpFactory,使BitmatpFactory工厂一直等待输入流,以收集数据进行解码试图getInputStream()

而且我没有看到输入流的任何close() - 期望tin块,这可能会导致更多的错误。

试试这个:

  • 创建线程分离HTTP连接,这样你就可以同时下载图像。只有

  • 解码位图文件下载后(您可能需要打开位图解码器的另一个流,但它甚至更快,更清晰那么你目前的解决方案)。

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

[更新]这些都是一些UTIL功能:

/** 
* 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; 
}