2017-09-05 95 views
-1

我想從我的Web API中提取圖像,並將它們填充到recyclerview中。我通過Web API獲取圖片 - 我使用Retrofit 2.0來使用API​​。圖像已被壓縮(大小範圍從100 - 300kb)。我面臨的問題是,將輸入流的內容寫入輸出流的while循環需要很長時間 - 我發現這個循環每個圖像需要7到11秒。下面是代碼來獲取圖片:InputStream寫入OutputStream的時間太長Android

if (postList.size() > 0) { 
        for (HousePostViewModel model : postList) { 
         Response<ResponseBody> pictureCall = service.getHousePostImage("Bearer " + sharedPreferences.getString("authorization_token", ""), model.getHousePostID(), currentActivity.getResources().getString(R.string.homenet_client_string)).execute(); 
         if (pictureCall.isSuccessful()) { 
          try { 
           InputStream inputStream = null; 
           FileOutputStream outputStream = null; 
           File profileFile = new File(currentActivity.getExternalCacheDir() + File.separator + generateRandomString()+"tempImage3.jpg"); 
           inputStream = new BufferedInputStream(pictureCall.body().byteStream()); 
           outputStream = new FileOutputStream(profileFile); 
           int c; 
           Log.i("START", "Starting to read the image"); 
           long timeInMS = System.currentTimeMillis(); 
           //This is the loop, where images take long to write to outputstream 
           while ((c = inputStream.read()) != -1) { 
            outputStream.write(c); 
           } 
           Picture picture = new Picture(profileFile); 
           pictureList.add(picture); 
           long finish = System.currentTimeMillis(); 
           long finalTime = finish - timeInMS; 
           Log.i("END", "Finished Reading file in " +finalTime+" ms"); 
           inputStream.close(); 
           outputStream.close(); 
          } catch (Exception error) { 

          } 
          } else { 
          errorString += pictureCall.errorBody().string(); 
         } 

         } 

        } 
      } 
     } else { 
      errorString += postCall.errorBody().string(); 
     } 

什麼你們會建議我嘗試一下,或做?或者有另一種從API獲取圖像數據的方式?

謝謝。

+3

嘗試讀取和寫入至少1 kb的塊,而不是一次一個字節。 *僅供參考:* ['Files.copy()'](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream- java.nio.file.Path-java.nio.file.CopyOption ...-)使用** 8 kb **緩衝區。 – Andreas

回答

1
while ((c = inputStream.read()) != -1) { 
    outputStream.write(c); 
} 

使用緩衝的I/O。希望我有降壓,每一次,我這個貼:

char[] buffer = new char[8192]; 
int count; 
while ((count = inputStream.read(buffer)) > 0) 
{ 
    outputStream.write(buffer, 0, count); 
} 

...你應該換一個BufferedOutputStreamFileOutputStream左右,這樣的:

outputStream = new BufferedOutputStream(new FileOutputStream(profileFile)); 

您還需要關閉流之前創建Picture