generateIconSet function

Future<int> generateIconSet(
  1. String path,
  2. List sets, {
  3. String? extension,
  4. String out = './out',
})

Returns the number of icons produced in the out dir given an image path, or -1 in case of error.

  • Additional icons can be produced by supplying a larger array.
  • The icons produced can be converted to a specified extension.

Implementation

Future<int> generateIconSet(String path, List sets,
    {String? extension, String out = './out'}) async {
  /// The base image to produce icons for.
  File file;
  List iconSets = [...sets];

  try {
    file = File(path);
  } catch (e) {
    print("error: Image is corrupted or doesn't exist'");
    return -1;
  }

  if (iconSets.isEmpty) {
    return 0;
  }

  // The number of icons produced.
  int count = 0;

  // Getting file data.
  List<String> filename = file.uri.pathSegments.last.split('.');
  String name = filename[0];
  String fileExt;

  try {
    fileExt = (extension ?? filename[1]).toLowerCase();
  } catch (e) {
    print("error: Invalid file: ${filename.join('.')}");
    return -1;
  }

  Function? imageDecoder = getDecoder(filename.join('.'));
  Function? encodeImage = getEncoder(fileExt);

  // Quit if we can't operate on the image.
  if (imageDecoder == null) {
    print('error: No available decoder.');
    return -1;
  } else if (encodeImage == null) {
    print('error: No available encoder.');
    return -1;
  } else {
    Image image;

    try {
      image = imageDecoder(file.readAsBytesSync());
    } catch (e) {
      print("error: Corrupt or incomplete image.");
      return -1;
    }

    // Create the output folder if it doesn't exist.
    Directory dir = Directory(out);
    if (!await dir.exists()) {
      dir.createSync();
    }

    // ICO format only supports sizes of up to 256px
    if (fileExt.toLowerCase() == 'ico') {
      normalizeSet(iconSets);
    }

    // Generate icons.
    for (var size in iconSets) {
      Image resized;

      // if size is an array then get the two measures...
      if (size is List) {
        resized = copyResize(image, width: size[0], height: size[1]);
      } else {
        // ... else output a square image.
        resized = copyResize(image, width: size);
      }

      File(
        '$out/$name-$size.$fileExt',
      ).writeAsBytesSync(encodeImage(resized));
      count++;
    }

    return count;
  }
}