Skip to content

Image Splitter — Rust 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 Rust 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: Rust (std only — no external crates).
//! 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.

/// 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 nested loops.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TileRect {
    pub row: usize,
    pub col: usize,
    /// Tile origin in the original image.
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

/// Clamp a rows/cols field value to the tool's 1-20 range. `f64::round`
/// rounds halves away from zero, matching JavaScript's Math.round for the
/// positive inputs a spinner produces; the clamp mirrors the NumberField
/// handler's `Math.max(1, Math.min(20, Math.round(v)))`.
pub fn clamp_grid(value: f64) -> u32 {
    value.round().clamp(1.0, 20.0) as u32
}

/// Shared tile metrics for a `width` x `height` image cut `rows` x `cols`
/// ways. Rust integer division 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. A grid finer
/// than the image (any dimension would round to 0) is the `Err` case,
/// carrying the same user-facing message the island shows.
pub fn tile_size(width: u32, height: u32, rows: u32, cols: u32) -> Result<(u32, u32), String> {
    let tile_w = width / cols;
    let tile_h = height / rows;
    if tile_w < 1 || tile_h < 1 {
        return Err("The grid is finer than the image — reduce rows or columns.".to_string());
    }
    Ok((tile_w, tile_h))
}

/// 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).
pub fn tile_rects(width: u32, height: u32, rows: u32, cols: u32) -> Result<Vec<TileRect>, String> {
    let (tile_w, tile_h) = tile_size(width, height, rows, cols)?;
    let mut rects = Vec::with_capacity(rows as usize * cols as usize);
    for row in 0..rows {
        for col in 0..cols {
            rects.push(TileRect {
                row: row as usize,
                col: col as usize,
                x: col * tile_w,
                y: row * tile_h,
                width: tile_w,
                height: tile_h,
            });
        }
    }
    Ok(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 hand-rolled stem
/// mirrors the island's `name.replace(/\.[^.]+$/, '')`: strip a final dot
/// only when at least one character follows it ("file." keeps its dot).
pub fn tile_name(file_name: &str, row: u32, col: u32) -> String {
    let stem = match file_name.rfind('.') {
        Some(i) if i + 1 < file_name.len() => &file_name[..i],
        _ => file_name,
    };
    format!("{stem}-{}x{}.png", 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 →