Skip to content

Photo Merge — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package photomerge ports the deterministic merge-cell layout of CosmoDev's
// photo-merge tool. Pure + deterministic, never panics.
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `photo-merge` tool, ported from
// src/tools/PhotoMerge.tsx.
//
// 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.
package photomerge

import (
	"errors"
	"math"
)

// ImageSize is a decoded image's dimensions, in pixels.
type ImageSize struct {
	Width  int
	Height int
}

// Layout is the merge arrangement, matching the island's layout buttons.
type Layout string

const (
	LayoutRow    Layout = "row"    // n cells in one horizontal strip
	LayoutColumn Layout = "column" // n cells in one vertical strip
	LayoutGrid   Layout = "grid"   // cells folded into ceil(sqrt(n)) columns
)

// Placement is where one image lands on the merged canvas.
type Placement struct {
	Col, Row int     // cell coordinates of this image
	Scale    float64 // aspect-preserving fit scale
	X, Y     int     // top-left corner on the canvas
	W, H     int     // fitted size in pixels
}

// MergedLayout is the canvas dimensions plus one placement per input image.
type MergedLayout struct {
	CanvasWidth, CanvasHeight int
	Cols, Rows                int
	Placements                []Placement
}

// MergeLayout computes the merge layout for a list of image sizes. It mirrors
// the deterministic half of merge() in PhotoMerge.tsx: cellW/cellH 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(cellW/w, cellH/h) (aspect-preserving, letterboxed) and
// centered inside its cell. math.Round rounds halves away from zero, which
// matches JS Math.round for the positive values produced here; the island's
// own "needs at least 2 photos" guard lives in the UI, not the geometry.
func MergeLayout(images []ImageSize, gap int, layout Layout) (MergedLayout, error) {
	if len(images) == 0 {
		return MergedLayout{}, errors.New("photomerge: need at least one image")
	}
	n := len(images)
	cellW, cellH := 0, 0
	for _, img := range images {
		if img.Width > cellW {
			cellW = img.Width
		}
		if img.Height > cellH {
			cellH = img.Height
		}
	}
	sqrtCols := int(math.Ceil(math.Sqrt(float64(n)))) // same IEEE sqrt+ceil as JS
	var cols, rows int
	switch layout {
	case LayoutRow:
		cols, rows = n, 1
	case LayoutColumn:
		cols, rows = 1, n
	case LayoutGrid:
		cols, rows = sqrtCols, (n+sqrtCols-1)/sqrtCols // integer ceil == Math.ceil(n/cols)
	default:
		return MergedLayout{}, errors.New("photomerge: unknown layout " + string(layout))
	}

	placements := make([]Placement, 0, n)
	for i, img := range images {
		col, row := i%cols, i/cols
		scale := math.Min(float64(cellW)/float64(img.Width), float64(cellH)/float64(img.Height))
		w := int(math.Round(float64(img.Width) * scale))
		h := int(math.Round(float64(img.Height) * scale))
		placements = append(placements, Placement{
			Col:   col,
			Row:   row,
			Scale: scale,
			X:     gap + col*(cellW+gap) + int(math.Round(float64(cellW-w)/2)),
			Y:     gap + row*(cellH+gap) + int(math.Round(float64(cellH-h)/2)),
			W:     w,
			H:     h,
		})
	}

	return MergedLayout{
		CanvasWidth:  cols*cellW + (cols+1)*gap,
		CanvasHeight: rows*cellH + (rows+1)*gap,
		Cols:         cols,
		Rows:         rows,
		Placements:   placements,
	}, nil
}

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 →