Skip to content

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

<?php
/**
 * image-resize-and-watermark — resize geometry + text-watermark layout.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `image-resize-and-watermark` tool,
 * ported from src/tools/ImageResizeWatermark.tsx.
 *
 * PHP's standard library can read image dimensions (getimagesize) but has no
 * font rasterizer — resampling, text drawing, and WebP encoding live in the
 * bundled-but-optional GD extension. This port covers the deterministic half:
 * the four resize modes, nine-anchor watermark placement, stroke width, and
 * output naming, all pure functions over the same numbers the canvas computes.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

const IRW_MARGIN = 8;                  // px gutter every anchor pins text in by
const IRW_FILL = '#ffffff';            // fillText colour
const IRW_STROKE = 'rgba(0,0,0,0.55)'; // strokeText outline colour
const IRW_FILL_ALPHA = 0.70;           // default opacity 70 / 100
const IRW_WEBP_QUALITY = 92;           // 0-100 scale <-> the tool's 0.92 toBlob
const IRW_EM_ADVANCE = 0.56;           // approx measureText: ~0.56 em per char

/** JS Math.round parity: half up, floor(x + 0.5) for the positive sizes used. */
function irw_js_round(float $x): int
{
    return (int) floor($x + 0.5);
}

/**
 * Output [w, h] for a resize mode ('none' | 'width' | 'height' | 'percent'),
 * mirroring the tool's process() arithmetic; derived sides clamp to >= 1 px.
 *
 * @return array{0: int, 1: int}
 */
function irw_target_size(string $mode, int $srcW, int $srcH, int $target): array
{
    $fit = static fn (float $n): int => max(1, irw_js_round($n));
    if ($mode === 'none') {
        return [$srcW, $srcH];
    }
    if ($mode === 'width') {
        return [$target, $fit($srcH / $srcW * $target)];
    }
    if ($mode === 'height') {
        return [$fit($srcW / $srcH * $target), $target];
    }
    if ($mode === 'percent') {
        return [$fit($srcW * $target / 100), $fit($srcH * $target / 100)];
    }
    throw new InvalidArgumentException("unknown resize mode: {$mode}");
}

/** Watermark font size: wmScale% of the shorter side, floored at 10 px. */
function irw_font_size(int $w, int $h, int $wmScale = 6): int
{
    return max(10, irw_js_round(min($w, $h) * $wmScale / 100));
}

/** Dark outline width for the strokeText pass: max(1, fontSize / 14). */
function irw_stroke_width(int $fontPx): float
{
    return max(1.0, $fontPx / 14);
}

/** Approximate canvas measureText: ~0.56 em per character (strlen counts
 * bytes; equal for the ASCII case, close enough for the approximation). */
function irw_text_width(string $text, int $fontPx): float
{
    return strlen($text) * $fontPx * IRW_EM_ADVANCE;
}

/** Horizontal anchor: left/right pin 8 px in, center balances the text box. */
function irw_anchor_x(string $anchor, int $box, float $item): float
{
    $col = $anchor[1]; // l | c | r
    if ($col === 'l') {
        return IRW_MARGIN;
    }
    if ($col === 'r') {
        return $box - $item - IRW_MARGIN;
    }
    return ($box - $item) / 2;
}

/** Vertical anchor: top baseline fs+8, middle 1/3 fs below center, bottom h-8. */
function irw_anchor_y(string $anchor, int $box, int $fontPx): float
{
    $row = $anchor[0]; // t | m | b
    if ($row === 't') {
        return $fontPx + IRW_MARGIN;
    }
    if ($row === 'b') {
        return $box - IRW_MARGIN;
    }
    return $box / 2 + $fontPx / 3;
}

/** Strip the old extension and tag -edited.webp, like the tool's outName. */
function irw_output_name(string $name): string
{
    return preg_replace('/\.[^.]+$/', '', $name) . '-edited.webp';
}

// Demo mirroring the C sibling: a 4032x3024 photo resized to 1280 wide.
[$w, $h] = irw_target_size('width', 4032, 3024, 1280);
$fs = irw_font_size($w, $h);
printf("%dx%d  font %dpx  stroke %.2fpx\n", $w, $h, $fs, irw_stroke_width($fs));
printf(
    "watermark 'CosmoDev' bottom-right at (%.0f, %.0f)\n",
    irw_anchor_x('br', $w, irw_text_width('CosmoDev', $fs)),
    irw_anchor_y('br', $h, $fs)
);
printf("IMG_4032.JPG -> %s\n", irw_output_name('IMG_4032.JPG'));
if (is_file('input.jpg')) {
    [$srcW, $srcH] = getimagesize('input.jpg'); // real stdlib dimension read
    [$tw, $th] = irw_target_size('width', $srcW, $srcH, 1280);
    printf("input.jpg is %dx%d -> %dx%d\n", $srcW, $srcH, $tw, $th);
}

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 →