saveImagesToDirectory static method

Future<List<String>> saveImagesToDirectory({
  1. required Iterable<String> images,
  2. required dynamic deleteThePreviousImages,
  3. required Directory saveDirectory,
  4. OnGenerateNewFileNameCallback? onGenerateNewFileName,
})

Saves a list of images to a specified directory.

This function is designed to work efficiently on mobile platforms, but it can also be used on other platforms. But it's not supported on web for now

When you have a list of cached image paths from a Quill document and you want to save them, you can use this function. It takes a list of image paths and copies each image to the specified directory. If the image path does not exist, it returns an empty string for that item.

Make sure that the image paths provided in the images list exist, and handle the cases where images are not found accordingly.

images: List of image paths to be saved. deleteThePreviousImages: Indicates whether to delete the original cached images after copying. saveDirectory: The directory where the images will be saved. startOfEachFile: Each file will have a name and it need to be unique but to make the file name is clear we will need a string represent the start of each file

Returns a list of paths to the newly saved images. For images that do not exist, their paths are returned as empty strings.

Example usage:

final documentsDir = await getApplicationDocumentsDirectory();
final savedImagePaths = await saveImagesToDirectory(
  images: cachedImagePaths,
  deleteThePreviousImages: true,
  saveDirectory: documentsDir,
  startOfEachFile: 'quill-image-', // default
);

Implementation

static Future<List<String>> saveImagesToDirectory({
  required Iterable<String> images,
  required deleteThePreviousImages,
  required Directory saveDirectory,
  OnGenerateNewFileNameCallback? onGenerateNewFileName,
}) async {
  _webIsNotSupported('saveImagesToDirectory');
  final newImagesFutures = images.map((cachedImagePath) async {
    final previousImageFile = File(cachedImagePath);
    final isPreviousImageFileExists = await previousImageFile.exists();

    if (!isPreviousImageFileExists) {
      return '';
    }

    final newImageFileExtension = path.extension(cachedImagePath); // with dot

    final dateTimeString = DateTime.now().toIso8601String();
    final newImageFileName = onGenerateNewFileName?.call(
          cachedImagePath,
          newImageFileExtension,
        ) ??
        'quill-image-$dateTimeString$newImageFileExtension';
    final newImagePath = path.join(saveDirectory.path, newImageFileName);
    final newImageFile = await previousImageFile.copy(newImagePath);
    if (deleteThePreviousImages) {
      await previousImageFile.delete();
    }
    return newImageFile.path;
  });
  // Await for the saving process for each image
  final newImages = await Future.wait(newImagesFutures);
  return newImages;
}