Skip to content

Image Splitter — C++ 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 C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Image splitter — tile geometry — C++17 port of the image-splitter tool.

#include <cstdint>
#include <iostream>
#include <string>
#include <vector>

// 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.
struct TileRect {
    int x, y, w, h;

    std::string str() const {
        return "src=(" + std::to_string(x) + ", " + std::to_string(y) + ") " +
               std::to_string(w) + "x" + std::to_string(h);
    }
};

// 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) — integer 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.
std::vector<TileRect> splitTiles(int width, int height, int rows, int cols) {
    const int tileW = width / cols;
    const int tileH = height / rows;
    std::vector<TileRect> tiles;
    tiles.reserve(static_cast<size_t>(rows) * cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            tiles.push_back({col * tileW, row * tileH, tileW, tileH});
        }
    }
    return tiles;
}

int main() {
    // 1024x768 image, 2 rows x 3 cols -> six 341x384 tiles.
    for (const TileRect &tile : splitTiles(1024, 768, 2, 3)) {
        std::cout << tile.str() << '\n';
    }
    return 0;
}

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 →