简体   繁体   English

无需第三方库即可下载远程映像的最佳方法?

[英]Best way to download remote images without third party libraries?

Welcome 欢迎

I need to download sycnronously (one at time) a lot of small remote images (between 50kb and 100kb) from a server and to store them as PNG in the device. 我需要从服务器上同步下载(一次一个)很多小型远程图像(介于50kb和100kb之间),并将其作为PNG存储在设备中。 I need to achieve this without third party libraries and I'm using this code but it is too munch slow: 我需要在没有第三方库的情况下实现此目标,并且正在使用以下代码,但速度太慢了:

        URL javaUrl = new URL(URLParser.parse(this.url));
        URLConnection connection = javaUrl.openConnection();

        InputStream input = new BufferedInputStream(javaUrl.openStream());
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            output.write(data, 0, count);
        }

        // conversion to bitmap
        InputStream in = new ByteArrayInputStream(output.toByteArray());
        Bitmap original = BitmapFactory.decodeStream(in);

        // storing bitmap as PNG file
        FileOutputStream out = new FileOutputStream(filename);
        original.compress(Bitmap.CompressFormat.PNG, 90, out);

        output.flush();
        output.close();
        input.close();
        in.close();
        original.recycle(); 

The problem is that the download is very slow. 问题是下载速度很慢。 With very fast WIFI internet in the device (13MB, download speed of 1.4mbytes/s), it is taking 3-4 seconds to download the image in the device, but only 100-200ms to download the image in my PC using google chrome for example. 设备中具有非常快的WIFI互联网(13MB,下载速度为1.4mbytes / s),使用谷歌浏览器将图像下载到设备中需要3-4秒,而仅需100-200ms即可将其下载到我的PC中例如。

It is something wrong in my download algorithm? 我的下载算法有问题吗? can be improved? 可以改善吗?

Thanks 谢谢

You have a totally unnecessary byte array in the middle. 您在中间有一个完全不必要的字节数组。 BitmapFactory.decodeStream() accepts an InputStream and you get an InputStream from URL.openStream() . BitmapFactory.decodeStream()接受InputStream然后从URL.openStream()获得InputStream

It might not give you the speed boost you're looking for, but it'll at least get rid of a completely useless step in your code. 它可能不会为您提供所需的速度提升,但至少会摆脱代码中完全无用的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM