dart Flutter -将ImageProvider保存到文件

xqnpmsa8  于 12个月前  发布在  Flutter
关注(0)|答案(2)|浏览(170)

我需要调整图像文件的大小并将其保存回缓存。要调整图像大小:

ImageProvider img = ResizeImage.resizeIfNeeded(1024, null, FileImage(File(path)));

字符串
我猜img对象包含了调整大小的图像数据。如何保存到文件中以便在需要时访问它?

uinbv5nw

uinbv5nw1#

如果有人在这里寻求答案,我很乐意分享我将ImageProvider保存到设备上的文件的方法。请参考下面的代码。

static Future<File?> saveImageProvider(ImageProvider imageProvider) async {
    const timeoutInMilliseconds = 10000;
    const loopDelay = Duration(milliseconds: 1000);
    final int maxAttempts = timeoutInMilliseconds ~/ loopDelay.inMilliseconds;
    int attemptCount = 0;
    File? savedFile;
    final appStorage = await getDefaultDestinationDirectory();

    imageProvider.resolve(const ImageConfiguration()).addListener(
      ImageStreamListener(
        (ImageInfo image, bool synchronousCall) async {
          ByteData? byteData =
              await image.image.toByteData(format: ImageByteFormat.png);
          if (byteData == null) return;
          savedFile = File('${appStorage.path}/${imageProvider.hashCode}.png');
          savedFile?.writeAsBytes(byteData.buffer.asUint8List());
        },
      ),
    );

    await Future.doWhile(() async {
      await Future.delayed(loopDelay);
      attemptCount++;

      if (attemptCount >= maxAttempts) return false;
      return savedFile == null;
    });

    return savedFile;
}

个字符

ecfdbz9o

ecfdbz9o2#

正如我所看到的,你已经调整了你的图像。你可以尝试这个代码来粘贴你的新图像。但要小心img,因为它必须像5D FF A0一样缓冲

ImageProvider img = ResizeImage.resizeIfNeeded(1024, null, FileImage(File(path)));

final File newImagePath = File("/example/path"); //pasting path

newImagePath.writeAsBytesSync(img);

字符串

相关问题