Skip to content

Image Resize & Watermark — Go source

Batch-resize images by width, height or percentage and stamp a text watermark with position, opacity and size control — entirely in your browser, nothing uploaded.

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

// image-resize-and-watermark — resize geometry + text-watermark layout.
//
// Language: Go (standard library only).
// CosmoDev polyglot showcase port of the `image-resize-and-watermark` tool,
// ported from src/tools/ImageResizeWatermark.tsx.
//
// The tool's layout math is pure; its raster pass is canvas-bound. Here the
// pixel half uses the stdlib image package (decode, nearest-neighbor resample
// where canvas drawImage would smooth); text raster and WebP encoding need
// golang.org/x/image, so they stay outside this port.
//
// display source — part of CosmoDev's polyglot tool pages.
package imageresizeandwatermark

import (
	"fmt"
	"image"
	"math"
	"regexp"
	"unicode/utf8"
)

// Watermark style, mirroring the TS canvas constants.
const (
	Margin      = 8.0  // px gutter every anchor pins text in by
	FillAlpha   = 0.70 // default opacity 70 / 100; stroke is 55%
	EmAdvance   = 0.56 // approx measureText: ~0.56 em per rune
	WebPQuality = 0.92 // canvas.toBlob quality; stdlib can't write WebP
)

// JSRound is JS Math.round parity: half up, spelled floor(x + 0.5).
func JSRound(x float64) int { return int(math.Floor(x + 0.5)) }

// TargetSize returns (w, h) for a resize mode ("none" | "width" | "height" |
// "percent"), mirroring the tool's process() arithmetic; sides clamp to >= 1.
func TargetSize(mode string, srcW, srcH, target int) (int, int) {
	fit := func(x float64) int {
		if n := JSRound(x); n > 1 {
			return n
		}
		return 1
	}
	sw, sh, t := float64(srcW), float64(srcH), float64(target)
	switch mode {
	case "none":
		return srcW, srcH
	case "width":
		return target, fit(sh / sw * t)
	case "height":
		return fit(sw / sh * t), target
	case "percent":
		return fit(sw * t / 100), fit(sh * t / 100)
	default:
		panic(fmt.Sprintf("image-resize-and-watermark: unknown resize mode %q", mode))
	}
}

// FontSize is the watermark font size: wmScale% of the shorter side, min 10 px.
func FontSize(w, h, wmScale int) int {
	short := w
	if h < w {
		short = h
	}
	if n := JSRound(float64(short) * float64(wmScale) / 100); n > 10 {
		return n
	}
	return 10
}

// StrokeWidth is the dark outline width: max(1, fontSize / 14).
func StrokeWidth(fontSize int) float64 { return math.Max(1, float64(fontSize)/14) }

// TextWidth approximates canvas measureText for a system sans-serif (~0.56 em
// per rune; real measurement needs a rasterizer from golang.org/x/image).
func TextWidth(text string, fontSize int) float64 {
	return float64(utf8.RuneCountInString(text)) * float64(fontSize) * EmAdvance
}

// AnchorX: left/right anchors pin Margin px in, center balances the text box.
func AnchorX(anchor string, box int, item float64) float64 {
	switch anchor[1] { // l, c, r
	case 'l':
		return Margin
	case 'r':
		return float64(box) - item - Margin
	default:
		return (float64(box) - item) / 2
	}
}

// AnchorY: top baseline fs+Margin, middle 1/3 fs below center, bottom h-Margin.
func AnchorY(anchor string, box, fontSize int) float64 {
	switch anchor[0] { // t, m, b
	case 't':
		return float64(fontSize) + Margin
	case 'b':
		return float64(box) - Margin
	default:
		return float64(box)/2 + float64(fontSize)/3
	}
}

var editedExt = regexp.MustCompile(`\.[^.]+$`)

// OutputName strips the old extension and tags -edited.webp (the tool's
// outName; outputs are WebP at quality 0.92 once an encoder is available).
func OutputName(name string) string {
	return editedExt.ReplaceAllString(name, "") + "-edited.webp"
}

// ResizeNearest resamples src to w x h with nearest-neighbor pixel
// replication — stdlib-pure where canvas drawImage would smooth.
func ResizeNearest(src image.Image, w, h int) *image.RGBA {
	b := src.Bounds()
	out := image.NewRGBA(image.Rect(0, 0, w, h))
	for y := 0; y < h; y++ {
		sy := b.Min.Y + y*b.Dy()/h
		for x := 0; x < w; x++ {
			sx := b.Min.X + x*b.Dx()/w
			out.Set(x, y, src.At(sx, sy))
		}
	}
	return out
}

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 →