2017-09-05 132 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