Skip to content

Image Splitter — Kotlin source

Split an image into an even grid of tiles — rows × columns with a live cut-line preview and per-tile or bulk PNG download. Runs entirely in your browser.

This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Image splitter — tile geometry — Kotlin port of the image-splitter tool.

/** One cut of the grid: the source rectangle that becomes a tile. In the
 *  browser tool this rect is drawImage'd into its own canvas and encoded
 *  to PNG; the geometry here is the deterministic part of that pipeline. */
data class TileRect(val x: Int, val y: Int, val width: Int, val height: Int) {
    override fun toString() = "src=($x, $y) ${width}x$height"
}

object ImageSplitter {
    /** Split a width x height image into rows x cols tiles, row-major.
     *  Mirrors splitToTiles in typescript.ts: tileW = floor(width / cols),
     *  tileH = floor(height / rows) — Int division IS Math.floor for
     *  positives, so a 1024px width over 3 cols yields 341px tiles and the
     *  last 1px column is dropped, exactly like the TS. */
    fun splitTiles(width: Int, height: Int, rows: Int, cols: Int): List<TileRect> {
        val tileW = width / cols
        val tileH = height / rows
        return (0 until rows).flatMap { row ->
            (0 until cols).map { col ->
                TileRect(col * tileW, row * tileH, tileW, tileH)
            }
        }
    }
}

// 1024x768 image, 2 rows x 3 cols -> six 341x384 tiles.
fun main() {
    ImageSplitter.splitTiles(1024, 768, 2, 3).forEach(::println)
}

Also available in 8 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →