Skip to content

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

"""image-splitter — tile geometry for an even rows × cols image grid cut.

Language: Python 3 (standard library only).
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.
"""

from __future__ import annotations

import math
import re
from dataclasses import dataclass

# Mirrors the island's /\.[^.]+$/ replacement: the final ".<ext>" suffix.
_EXTENSION = re.compile(r"\.[^.]+$")


@dataclass(frozen=True)
class TileRect:
    """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. ``row``/``col`` are 0-based, row-major like the island's loops.
    """

    row: int
    col: int
    x: int
    y: int
    width: int
    height: int


def clamp_grid(value: float) -> int:
    """Clamp a rows/cols field value to the tool's 1-20 range.

    ``math.floor(value + 0.5)`` mirrors JavaScript's Math.round (half up);
    Python's built-in round() would round halves to even instead.
    """
    return max(1, min(20, math.floor(value + 0.5)))


def tile_size(width: int, height: int, rows: int, cols: int) -> tuple[int, int]:
    """Shared tile metrics for a width x height image cut rows x cols ways.

    ``width // cols`` 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.

    Raises:
        ValueError: with the island's user-facing message when the grid is
            finer than the image (any tile dimension would round to 0).
    """
    tile_w = width // cols
    tile_h = height // rows
    if tile_w < 1 or tile_h < 1:
        raise ValueError("The grid is finer than the image — reduce rows or columns.")
    return tile_w, tile_h


def tile_rects(width: int, height: int, rows: int, cols: int) -> list[TileRect]:
    """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.
    """
    tile_w, tile_h = tile_size(width, height, rows, cols)
    return [
        TileRect(row=row, col=col, x=col * tile_w, y=row * tile_h, width=tile_w, height=tile_h)
        for row in range(rows)
        for col in range(cols)
    ]


def tile_name(file_name: str, row: int, col: int) -> str:
    """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.
    """
    stem = _EXTENSION.sub("", file_name)
    return f"{stem}-{row + 1}x{col + 1}.png"

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 →