Skip to content

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

// Image splitter — tile geometry — Java port of the image-splitter tool.

import java.util.ArrayList;
import java.util.List;

/** 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. */
record TileRect(int x, int y, int width, int height) {
    @Override
    public String toString() {
        return "src=(" + x + ", " + y + ") " + width + "x" + height;
    }
}

public class ImageSplitter {

    /** 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. */
    static List<TileRect> splitTiles(int width, int height, int rows, int cols) {
        int tileW = width / cols;
        int tileH = height / rows;
        List<TileRect> tiles = new ArrayList<>(rows * cols);
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                tiles.add(new TileRect(col * tileW, row * tileH, tileW, tileH));
            }
        }
        return tiles;
    }

    // 1024x768 image, 2 rows x 3 cols -> six 341x384 tiles.
    public static void main(String[] args) {
        for (TileRect tile : splitTiles(1024, 768, 2, 3)) {
            System.out.println(tile);
        }
    }
}

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 →