使用OkHttp将大量图像下载到SD卡

时间:2016-02-13 11:37:23

标签: android image performance okhttp

因此我的应用程序的一部分使用IntentService向SdCard下载了大量(~1600)图像。我以前使用过Glide,但现在想切换到OkHttp,因为它看起来更快,耗电更少。这是我目前的代码:

for (int i = 1; i < 1600; i++) {
        try {
            Request request = new Request.Builder()
                    .url(imageUrls[i])
                    .build();

            Response response = client.newCall(request).execute();
            File testDirectory = new File(Environment.getExternalStorageDirectory() 
                                                                  + "/downloadTest");
            if (!testDirectory.exists())
                 testDirectory.mkdirs();
            OutputStream outputStream = new FileOutputStream(new File(testDirectory, 
                                                          "testImage" + i + ".png"));
            InputStream inputStream = response.body().byteStream();
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inputStream.read(buffer, 0, buffer.length)) >= 0)
                outputStream.write(buffer, 0, read);
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

有什么方法可以优化此代码以加快下载速度?

2 个答案:

答案 0 :(得分:5)

您可以使用Okio代替InputStream / OutputStream来保存一些副本。像这样:

BufferedSink sink = Okio.buffer(Okio.sink(new File(testDirectory, "testImage" + i + ".png")));
sink.writeAll(response.body().source());
sink.close();
response.body().close();

请参阅this post,了解为何更快的解释。

答案 1 :(得分:0)

最简单的方法是:

InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

并将位图保存为jpg:

File file = new File (myDir, fname);
if (file.exists ()) file.delete (); 
try {
       FileOutputStream out = new FileOutputStream(file);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();

} catch (Exception e) {
       e.printStackTrace();
}