Skip to content

Image Splitter — JavaScript 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 JavaScript 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: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `image-splitter` tool, ported from
 * src/tools/ImageSplitter.tsx.
 *
 * The live tool decodes the upload with createImageBitmap, rasterizes each
 * grid cell via canvas drawImage and re-encodes it to PNG — all canvas-bound
 * and omitted here. This port carries the deterministic half of split(): the
 * floor-divided tile metrics, the "grid finer than the image" guard, the
 * row-major cell enumeration, and the `<name>-<row>x<col>.png` output naming,
 * so any host can reproduce the exact cut lines and file names before pixels
 * are ever touched.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

/**
 * Clamp a rows/cols field value to the tool's 1-20 range. Mirrors the
 * NumberField onChange handler: Math.max(1, Math.min(20, Math.round(v))).
 */
export function clampGrid(value) {
  return Math.max(1, Math.min(20, Math.round(value)));
}

/**
 * Shared tile metrics for a width x height image cut rows x cols ways.
 *
 * tileW = floor(width / cols) and tileH = floor(height / rows) — the dropped
 * remainder pixels match the browser tool exactly: a 1024px width over 3
 * cols yields 341px tiles and the last 1px column is never drawn. A grid
 * finer than the image (any dimension rounds to 0) throws the same user
 * facing message the island shows.
 *
 * @returns {{tileW: number, tileH: number}}
 * @throws {Error} when the grid is finer than the image.
 */
export function tileSize(width, height, rows, cols) {
  const tileW = Math.floor(width / cols);
  const tileH = Math.floor(height / rows);
  if (tileW < 1 || tileH < 1) {
    throw new Error('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). Each rect is the drawImage source rectangle: x/y is where
 * the tile starts in the original image, width/height its size.
 *
 * @returns {Array<{row: number, col: number, x: number, y: number, width: number, height: number}>}
 */
export function tileRects(width, height, rows, cols) {
  const { tileW, tileH } = tileSize(width, height, rows, cols);
  const rects = [];
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      rects.push({ row, col, x: col * tileW, y: row * tileH, width: tileW, height: tileH });
    }
  }
  return rects;
}

/**
 * Output file name for one tile. Strips the source extension exactly like
 * the island (name.replace(/\.[^.]+$/, '')) then appends the 1-based grid
 * position: photo.jpg at row 0, col 2 becomes photo-1x3.png — matching the
 * `-<row+1>x<col+1>.png` scheme the tool's download buttons use.
 */
export function tileName(fileName, row, col) {
  return `${fileName.replace(/\.[^.]+$/, '')}-${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 →