flutter应用程序中的隔离是否存在内存问题?

时间:2019-10-28 10:27:54

标签: flutter

我对flutter应用程序的内存有问题,在使用compute时,我将此行放在compute的函数参数中:

var image = imglib.Image.fromBytes(values[1].width, values[1].height, values[1].planes[0].bytes, format: imglib.Format.bgra);

并循环运行,每次内存持续增长,然后内存不足,应用崩溃。

如果我没有那条线,则内存稳定在40mb。因此,我认为在计算中,计算功能完成后并没有清除它。

有人遇到同样的问题吗?

编辑:

这是我实现计算的方式:

image = await compute(getCropImage, [copyFaces, streamImg]);

在getCropImage中:

Future<imglib.Image> getCropImage(List<dynamic> values) async {
  var image = imglib.Image.fromBytes(values[1].width, values[1].height, values[1].planes[0].bytes, format: imglib.Format.bgra);

  double topLeftX = values[0][0].boundingBox.topLeft.dx.round() -
  (values[0][0].boundingBox.width * 0.2);
  double topLeftY = values[0][0].boundingBox.topLeft.dy.round() -
  (values[0][0].boundingBox.height * 0.2);
  double width = values[0][0].boundingBox.width.round() +
  (values[0][0].boundingBox.width * 0.4);
  double height = values[0][0].boundingBox.height.round() +
  (values[0][0].boundingBox.height * 0.4);
  if (topLeftX <= 0) {
    topLeftX = 25;
  }
  if (topLeftY <= 0) {
    topLeftY = 25;
  }
  if ((topLeftX + width) >= values[1].width) {
    width = values[1].width - topLeftX - 25;
  }
  if ((topLeftY + height) >= values[1].height) {
    height = values[1].height - topLeftY - 25;
  }

  return imglib.copyCrop(
      image, topLeftX.round(), topLeftY.round(), width.round(), height.round());
}

带有imglib的是Image包:

import 'package:image/image.dart' as imglib;

每次我叫它时,内存都会不断增长。

2 个答案:

答案 0 :(得分:0)

要尝试复制您的样本,我必须先从ui.Image进行转换:

Future<Uint8List> _bytePng(ui.Image image) async {
  ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.rawRgba);
  Uint8List byteList = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
  return byteList;
}

运行示例的简化版本:

imglib.Image image2 = await compute(_getImage, [image1.width, image1.height, byteList]);


Future<imglib.Image> _getImage(List<dynamic> values) async {
  var temp = imglib.Image.fromBytes(values[0], values[1], values[2], format: imglib.Format.bgra);

  var rng = new Random().nextInt(50);
  imglib.Image cropped = imglib.copyCrop(temp, 0, 0, temp.width - rng, temp.height - rng);

  return cropped;
}

但是我无法看到内存失控。因此,您可能还会发生其他事情。

答案 1 :(得分:0)

对于像我们这样的入门者,我们需要了解,计算功能不过是隔离本身。创建的调用越多,将需要的内存就越多。这个参考 Isolates spawn will take ~ 2mb of ram 因此,即使您可能会说我只是在计算并返回结果,所以我们也需要尽量减少隔离,以便隔离可能会调用GC,但是在您滚动和缓存或使用隔离或代码做某件事时却没有隔离区中的内存可能会影响巨大的内存占用。

因此,我建议您创建一个隔离区,然后执行您想做的任何事情,完成所有操作后,复制面部,然后关闭隔离区。

watch this video also to know how to use isolate