saveBytesToFile function

Future<void> saveBytesToFile({
  1. required File file,
  2. ImageFileFormat? format,
  3. required Uint8List imageData,
  4. required int width,
  5. required int height,
})

Saves the given imageData to the given file.

The file's extension is used to infer the desired image format. The extension may be one of ".png", ".jpg", ".tif", or ".tga".

To override the file extension, or use a file name without an extension, specify the desired format.

Implementation

Future<void> saveBytesToFile({
  required File file,
  ImageFileFormat? format,
  required Uint8List imageData,
  required int width,
  required int height,
}) async {
  late ImageFileFormat imageFormat;
  if (format != null) {
    imageFormat = format;
  } else {
    final imageFormatFromFile = _getImageFileFormatFromFilePath(file.path);
    if (imageFormatFromFile == null) {
      throw Exception('Cannot save image to file with invalid extension and no explicit image type: ${file.path}');
    }
    imageFormat = imageFormatFromFile;
  }

  // Convert the pixel data to the desired format.
  late List<int> formattedImageData;
  switch (imageFormat) {
    case ImageFileFormat.png:
      formattedImageData = imageFormats.encodePng(
        imageFormats.Image.fromBytes(width, height, imageData),
      );
      break;
    case ImageFileFormat.jpeg:
      formattedImageData = imageFormats.encodeJpg(
        imageFormats.Image.fromBytes(width, height, imageData),
      );
      break;
    case ImageFileFormat.tiff:
      throw UnimplementedError('Tiff images are not supported in save()');
    case ImageFileFormat.targa:
      formattedImageData = imageFormats.encodeTga(
        imageFormats.Image.fromBytes(width, height, imageData),
      );
      break;
  }

  // Write the formatted pixels to the given file.
  await file.writeAsBytes(formattedImageData);
}