如何正确下载并保存图像的列表? [英] How do I properly download and save a list of images?

查看:203
本文介绍了如何正确下载并保存图像的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有URL的图像的列表,并想下载和保存每个图像。不幸的是,我不断收到一个内存异常,由于耗尽堆空间。最后一次尝试挽救了两个图像,然后扔透支堆空间,试图分配33554464字节。

我的code如下所示。逻辑似乎是正确的,但我相信,异步调用可能有故障。有一些调整,我应该做会导致下载是连续的?还是有我应该利用其他方法?

进口'包:HTTP / http.dart'为http;
进口'镖:IO';主(){
  //禄是一组有效的URL
  // ...  loc.forEach(retrieveImage)
}无效retrieveImage(字符串位置){
  URI URI = Uri.parse(位置);
  字符串名称= uri.pathSegments.last;  打印(读$位置);
  http.readBytes(位置)。然后((图像)=> saveImage(名称,图片));}无效saveImage(字符串名称,变种数据){
  新的文件($ {名})
    ..writeAsBytesSync(数据);
  打印(名);
}


解决方案

如果您想要下载顺序它们,您可以切换到的 Future.forEach 。此枚举通过集合执行用于每一个的功能,但在等待未来该函数返回在移动到下一个前完成。它反过来,返回一个未来一旦最终迭代已经完成了完成

而不是

loc.forEach(retrieveImage);

使用

Future.forEach(LOC,retrieveImage);

然后确保 retrieveImage 返回未来:

未来retrieveImage(字符串位置){
  URI URI = Uri.parse(位置);
  字符串名称= uri.pathSegments.last;  打印(读$位置);
  返回http.readBytes(位置)。然后((图像)=> saveImage(名称,图片));
}

I have a list of image of URLs and would like to download and save each image. Unfortunately, I keep receiving an Out of Memory exception due to an exhausted heap space. The last attempt saved two images and then threw "Exhausted heap space, trying to allocate 33554464 bytes".

My code is shown below. The logic seems correct but I believe the asynchronous calls may be at fault. Is there some adjustment I should make to cause downloading to be sequential? Or is there another method I should be utilizing?

import 'package:http/http.dart' as http;
import 'dart:io';

main() {
  // loc is a Set of valid URLs
  // ...

  loc.forEach(retrieveImage)
}

void retrieveImage(String location) {
  Uri uri = Uri.parse(location);
  String name = uri.pathSegments.last;

  print("Reading $location");
  http.readBytes(location).then((image) => saveImage(name, image));

} 

void saveImage(String name, var data) {
  new File("${name}")
    ..writeAsBytesSync(data);
  print(name);
}

解决方案

If you want to download them sequentially, you can switch to Future.forEach. This enumerators through a collection executing a function for each, but waiting for the Future that the function returns to complete before moving on to the next. It, in turn, returns a future that completes once the final iteration has completed.

Instead of

loc.forEach(retrieveImage);

use

Future.forEach(loc, retrieveImage);

and then ensure retrieveImage returns the future:

Future retrieveImage(String location) {
  Uri uri = Uri.parse(location);
  String name = uri.pathSegments.last;

  print("Reading $location");
  return http.readBytes(location).then((image) => saveImage(name, image));
}

这篇关于如何正确下载并保存图像的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆