Skip to content

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

"""image-resize-and-watermark — resize geometry + text-watermark layout.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `image-resize-and-watermark` tool,
ported from src/tools/ImageResizeWatermark.tsx.

Python's stdlib has no image codec or font rasterizer, so this port covers the
deterministic half the tool computes before any pixels move: the four resize
modes, the nine-anchor watermark placement, stroke width, and output naming.
Decode, resampling, text rasterization, and WebP encode need Pillow or
ImageMagick (third-party) at the edges.

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

from __future__ import annotations

import math
import re

MARGIN = 8  # px gutter every anchor pins text in by
FILL = "#ffffff"  # fillText colour
STROKE = "rgba(0,0,0,0.55)"  # strokeText outline colour
FILL_ALPHA = 0.70  # default opacity 70 / 100
STROKE_ALPHA = 0.55
WEBP_QUALITY = 92  # 0-100 scale <-> the tool's 0.92 canvas.toBlob quality
EM_ADVANCE = 0.56  # approx measureText: ~0.56 em average advance per char


def js_round(x: float) -> int:
    """JS Math.round parity: half up, spelled floor(x + 0.5) — Python's round
    is banker's rounding and would send .5 cases the wrong way."""
    return math.floor(x + 0.5)


def target_size(mode: str, src_w: int, src_h: int, target: int) -> tuple[int, int]:
    """Output (w, h) for a resize mode: none | width | height | percent.

    Mirrors the tool's process() arithmetic; every derived dimension clamps
    to >= 1 px, as in Math.max(1, Math.round(...)).
    """

    def fit(n: float) -> int:
        return max(1, js_round(n))

    if mode == "none":
        return src_w, src_h
    if mode == "width":
        return target, fit(src_h / src_w * target)
    if mode == "height":
        return fit(src_w / src_h * target), target
    if mode == "percent":
        return fit(src_w * target / 100), fit(src_h * target / 100)
    raise ValueError(f"unknown resize mode: {mode}")


def font_size(w: int, h: int, wm_scale: int = 6) -> int:
    """Watermark font size: wm_scale% of the shorter side, floored at 10 px."""
    return max(10, js_round(min(w, h) * wm_scale / 100))


def stroke_width(font_px: int) -> float:
    """Dark outline width for the strokeText pass: max(1, fontSize / 14)."""
    return max(1, font_px / 14)


def text_width(text: str, font_px: int) -> float:
    """Approximate canvas measureText for a system sans-serif: ~0.56 em per
    character (real measurement needs a rasterized font, out of stdlib)."""
    return len(text) * font_px * EM_ADVANCE


def anchor_x(anchor: str, box: int, item: float) -> float:
    """Horizontal anchor: left/right pin 8 px in, center balances the box."""
    col = anchor[1]  # l | c | r
    if col == "l":
        return MARGIN
    if col == "r":
        return box - item - MARGIN
    return (box - item) / 2


def anchor_y(anchor: str, box: int, font_px: int) -> float:
    """Vertical anchor: top baseline fs+8, middle 1/3 fs below center, h-8."""
    row = anchor[0]  # t | m | b
    if row == "t":
        return font_px + MARGIN
    if row == "b":
        return box - MARGIN
    return box / 2 + font_px / 3


def output_name(name: str) -> str:
    """Strip the old extension and tag -edited.webp, like the tool's outName."""
    return re.sub(r"\.[^.]+$", "", name) + "-edited.webp"


if __name__ == "__main__":
    # Same demo as the C sibling: a 4032x3024 photo resized to 1280 wide.
    w, h = target_size("width", 4032, 3024, 1280)
    fs = font_size(w, h)
    print(f"{w}x{h}  font {fs}px  stroke {stroke_width(fs):.2f}px")
    print(f"watermark 'CosmoDev' bottom-right at ({anchor_x('br', w, text_width('CosmoDev', fs)):.0f}, {anchor_y('br', h, fs):.0f})")
    print(f"IMG_4032.JPG -> {output_name('IMG_4032.JPG')}")

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 →