createTiles static method

Future<void> createTiles(
  1. String inputPath,
  2. String outputTemplate,
  3. int tileSize
)

Создание тайлов из изображения

Implementation

static Future<void> createTiles(
  String inputPath,
  String outputTemplate,
  int tileSize,
) async {
  final file = File(inputPath);
  final bytes = await file.readAsBytes();
  final image = img.decodeImage(bytes);

  if (image == null) {
    throw Exception('Не удалось декодировать изображение: $inputPath');
  }

  final width = image.width;
  final height = image.height;
  final tilesX = (width / tileSize).ceil();
  final tilesY = (height / tileSize).ceil();

  for (int y = 0; y < tilesY; y++) {
    for (int x = 0; x < tilesX; x++) {
      final tileX = x * tileSize;
      final tileY = y * tileSize;
      final tileWidth = (tileX + tileSize > width) ? width - tileX : tileSize;
      final tileHeight = (tileY + tileSize > height)
          ? height - tileY
          : tileSize;

      final tile = img.copyCrop(
        image,
        x: tileX,
        y: tileY,
        width: tileWidth,
        height: tileHeight,
      );

      final tilePath = outputTemplate
          .replaceAll('{0}', x.toString())
          .replaceAll('{1}', y.toString());
      final tileFile = File(tilePath);
      await tileFile.writeAsBytes(img.encodePng(tile));
    }
  }
}