Skip to content

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

<?php
/**
 * image-splitter — tile geometry for an even rows × cols image grid cut.
 *
 * Language: PHP 8.1+ (standard library only) — readonly promoted properties.
 * CosmoDev polyglot showcase port of the `image-splitter` tool, ported from
 * src/tools/ImageSplitter.tsx.
 *
 * The live tool rasterizes each grid cell through a canvas and re-encodes it
 * to PNG (canvas-bound), so this port carries the deterministic half of
 * split(): floor-divided tile metrics, the "grid finer than the image"
 * guard, row-major cell enumeration, and the `<name>-<row>x<col>.png`
 * output naming.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** 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. */
final class TileRect
{
    public function __construct(
        public readonly int $row,
        public readonly int $col,
        public readonly int $x,
        public readonly int $y,
        public readonly int $width,
        public readonly int $height,
    ) {}
}

/** Clamp a rows/cols field value to the tool's 1-20 range. PHP's round()
 * rounds halves away from zero, matching JavaScript's Math.round for the
 * positive inputs a spinner produces; the max/min clamp mirrors the
 * NumberField handler's Math.max(1, Math.min(20, Math.round(v))). */
function clamp_grid(float $value): int
{
    return max(1, min(20, (int) round($value)));
}

/**
 * Shared tile metrics for a width x height image cut rows x cols ways.
 *
 * intdiv() truncates toward zero, which 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 browser tool.
 *
 * @return array{0: int, 1: int} the [tileW, tileH] pair.
 * @throws \RuntimeException with the island's user-facing message when the
 *         grid is finer than the image (any dimension would round to 0).
 */
function tile_size(int $width, int $height, int $rows, int $cols): array
{
    $tileW = intdiv($width, $cols);
    $tileH = intdiv($height, $rows);
    if ($tileW < 1 || $tileH < 1) {
        throw new RuntimeException('The grid is finer than the image — reduce rows or columns.');
    }
    return [$tileW, $tileH];
}

/**
 * Enumerate every tile as a source rectangle, row-major (the same order the
 * island's nested for-loops visit cells, and the order tiles appear in the
 * output grid). x/y is where the tile starts in the original image.
 *
 * @return list<TileRect>
 * @throws \RuntimeException when the grid is finer than the image.
 */
function tile_rects(int $width, int $height, int $rows, int $cols): array
{
    [$tileW, $tileH] = tile_size($width, $height, $rows, $cols);
    $rects = [];
    for ($row = 0; $row < $rows; $row++) {
        for ($col = 0; $col < $cols; $col++) {
            $rects[] = new TileRect($row, $col, $col * $tileW, $row * $tileH, $tileW, $tileH);
        }
    }
    return $rects;
}

/**
 * Output file name for one tile: the extensionless source name plus the
 * 1-based grid position, e.g. photo.jpg at row 0, col 2 -> photo-1x3.png —
 * matching the download file names the tool generates. The same
 * /\.[^.]+$/ regex the island uses strips the extension.
 */
function tile_name(string $fileName, int $row, int $col): string
{
    $stem = preg_replace('/\.[^.]+$/', '', $fileName);
    return sprintf('%s-%dx%d.png', $stem, $row + 1, $col + 1);
}

Also available in 13 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 →