Flutter - 将 ImageProvider 保存到文件

问题描述 投票:0回答:2

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

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

我猜

img
对象包含调整大小的图像数据。如何将其保存到文件以便需要时访问?

image flutter dart image-resizing
2个回答
0
投票

如果有人在这里寻求答案,我很乐意分享我将 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;
}
static Future<Directory> getDefaultDestinationDirectory() async {
    final preferredDirectory = Directory('/storage/emulated/0/Pictures');

    return Platform.isAndroid
        ? preferredDirectory.existsSync()
            ? preferredDirectory
            : await getApplicationDocumentsDirectory()
        : await getApplicationSupportDirectory();
}

-1
投票

正如我所见,您已经调整了图像大小。您可以尝试使用此代码来粘贴新图像。但要小心

img
,因为它必须像
5D FF A0

一样缓冲
ImageProvider img = ResizeImage.resizeIfNeeded(1024, null, FileImage(File(path)));

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

newImagePath.writeAsBytesSync(img);
© www.soinside.com 2019 - 2024. All rights reserved.