2013-04-03 132 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; 
}