【问题标题】:Use OkHttp to download lots of images to sd card使用 OkHttp 下载大量图片到 sd 卡
【发布时间】:2023-03-17 16:47:02
【问题描述】:

因此,我的应用程序的一部分使用 IntentService 将大量(~1600)图像下载到 SdCard。我以前使用 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();
        }
    }

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

【问题讨论】:

    标签: android image performance okhttp


    【解决方案1】:

    您可以使用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 了解为什么这样更快。

    【讨论】:

    【解决方案2】:

    最简单的方法是:

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

    【讨论】:

    • 解码位图只是为了再次压缩它会不会效率低下?
    • 您需要获取位图的地方。如果你想让下载速度更快,你可以使用多个 AsyncTasks。我希望我能帮助你。 :)
    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 2011-03-25
    • 2023-04-05
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多