Skip to content

Photo Merge — Python source

Combine photos side by side, stacked, or in a grid — uniform cells, adjustable gap, one PNG out. Runs entirely in your browser.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""photo-merge — merge-cell layout for side-by-side, stacked and grid merges.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `photo-merge` tool, ported from
src/tools/PhotoMerge.tsx.

Why this file exists: the live island is canvas-bound — createImageBitmap
decodes each photo, drawImage composites it, canvas.toBlob encodes the PNG,
and the cells are painted over a #0f172a background. Those calls consume pure
geometry (uniform cell size, per-image fit scale, centered placement); this
port extracts that geometry so the math is inspectable without a browser.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import math
from dataclasses import dataclass


@dataclass(frozen=True)
class ImageSize:
    """A decoded image's dimensions, in pixels."""

    width: int
    height: int


@dataclass(frozen=True)
class Placement:
    """Where one image lands on the merged canvas."""

    col: int
    row: int
    scale: float
    x: int
    y: int
    w: int
    h: int


def _js_round(value: float) -> int:
    """JS ``Math.round``: halves round toward +infinity.

    Python's built-in round() is banker's rounding (2.5 -> 2), which would
    drift from the browser on x.5 cell edges; floor(value + 0.5) matches it.
    """
    return math.floor(value + 0.5)


def merge_layout(
    images: list[ImageSize], gap: int = 12, layout: str = "row"
) -> dict:
    """Compute the merge layout for a list of image sizes.

    Mirrors the deterministic half of ``merge()`` in PhotoMerge.tsx:
    cellW/cellH are the largest input dimensions, "row" stacks n cells
    horizontally, "column" vertically, and "grid" folds them into
    ceil(sqrt(n)) columns. The canvas is cells plus perimeter gaps, and each
    image is scaled by min(cellW / w, cellH / h) (aspect-preserving,
    letterboxed) and centered inside its cell.

    Returns a dict with canvas_width, canvas_height, cols, rows and one
    Placement per image.
    """
    n = len(images)
    cell_w = max(img.width for img in images)
    cell_h = max(img.height for img in images)
    if layout == "row":
        cols, rows = n, 1
    elif layout == "column":
        cols, rows = 1, n
    else:  # grid
        cols, rows = math.ceil(math.sqrt(n)), math.ceil(n / math.ceil(math.sqrt(n)))

    placements: list[Placement] = []
    for i, img in enumerate(images):
        col, row = i % cols, i // cols
        scale = min(cell_w / img.width, cell_h / img.height)
        w = _js_round(img.width * scale)
        h = _js_round(img.height * scale)
        placements.append(
            Placement(
                col=col,
                row=row,
                scale=scale,
                x=gap + col * (cell_w + gap) + _js_round((cell_w - w) / 2),
                y=gap + row * (cell_h + gap) + _js_round((cell_h - h) / 2),
                w=w,
                h=h,
            )
        )

    return {
        "canvas_width": cols * cell_w + (cols + 1) * gap,
        "canvas_height": rows * cell_h + (rows + 1) * gap,
        "cols": cols,
        "rows": rows,
        "placements": placements,
    }

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 →