Skip to content

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

/// A decoded image's dimensions, in pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImageSize {
    pub width: u32,
    pub height: u32,
}

/// Where one image lands on the merged canvas.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Placement {
    pub col: usize,
    pub row: usize,
    pub scale: f64,
    pub x: i64,
    pub y: i64,
    pub w: u32,
    pub h: u32,
}

/// The merge arrangement, matching the island's Layout buttons.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
    /// n cells in one horizontal strip.
    Row,
    /// n cells in one vertical strip.
    Column,
    /// cells folded into ceil(sqrt(n)) columns.
    Grid,
}

/// Canvas dimensions plus one placement per input image.
#[derive(Clone, Debug, PartialEq)]
pub struct MergedLayout {
    pub canvas_width: u32,
    pub canvas_height: u32,
    pub cols: usize,
    pub rows: usize,
    pub placements: Vec<Placement>,
}

/// Compute the merge layout for a list of image sizes.
///
/// Mirrors the deterministic half of `merge()` in PhotoMerge.tsx:
/// cell_w/cell_h are the largest input dimensions, so no photo is upscaled
/// away; the canvas is cells plus perimeter gaps (cols + 1 horizontal, rows + 1
/// vertical); each image is scaled by min(cell_w / w, cell_h / h)
/// (aspect-preserving, letterboxed) and centered inside its cell. `f64::round`
/// rounds halves away from zero, which matches JS Math.round for the positive
/// values produced here; ceil(sqrt(n)) uses the same IEEE sqrt + ceil as JS.
pub fn merge_layout(images: &[ImageSize], gap: u32, layout: Layout) -> MergedLayout {
    let n = images.len();
    let cell_w = images.iter().map(|i| i.width).max().unwrap_or(0);
    let cell_h = images.iter().map(|i| i.height).max().unwrap_or(0);
    let cols = match layout {
        Layout::Row => n,
        Layout::Column => 1,
        Layout::Grid => (n as f64).sqrt().ceil() as usize,
    };
    let rows = match layout {
        Layout::Row => 1,
        Layout::Column => n,
        Layout::Grid => (n + cols - 1) / cols, // integer ceil, == Math.ceil(n/cols)
    };

    let placements = images
        .iter()
        .enumerate()
        .map(|(i, img)| {
            let col = i % cols;
            let row = i / cols;
            let scale = f64::min(cell_w as f64 / img.width as f64, cell_h as f64 / img.height as f64);
            let w = (img.width as f64 * scale).round() as u32;
            let h = (img.height as f64 * scale).round() as u32;
            let center = |cell: u32, fit: u32| ((cell as f64 - fit as f64) / 2.0).round() as i64;
            Placement {
                col,
                row,
                scale,
                x: gap as i64 + (col * (cell_w as usize + gap as usize)) as i64 + center(cell_w, w),
                y: gap as i64 + (row * (cell_h as usize + gap as usize)) as i64 + center(cell_h, h),
                w,
                h,
            }
        })
        .collect();

    MergedLayout {
        canvas_width: (cols as u32) * cell_w + (cols as u32 + 1) * gap,
        canvas_height: (rows as u32) * cell_h + (rows as u32 + 1) * gap,
        cols,
        rows,
        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 →