Skip to content

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

/**
 * image-resize-and-watermark — client-side batch resize + text watermark.
 *
 * Language: JavaScript (ES2020; browser canvas APIs, no imports, no dependencies).
 * CosmoDev polyglot showcase port of the `image-resize-and-watermark` tool,
 * ported from src/tools/ImageResizeWatermark.tsx.
 *
 * The live tool keeps every pixel local: createImageBitmap decodes, canvas
 * rasterizes and encodes WebP. Everything below except measureText and the
 * canvas raster pass is pure, deterministic geometry — the same numbers the
 * React island computes for its four resize modes and nine watermark anchors.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

export const MARGIN = 8; // px gutter every anchor pins text in by
export const WEBP_QUALITY = 0.92; // canvas.toBlob quality
export const ANCHORS = ['tl', 'tc', 'tr', 'ml', 'c', 'mr', 'bl', 'bc', 'br'];

/**
 * Output dimensions for a resize mode ('none' | 'width' | 'height' |
 * 'percent'), mirroring the tool's process() arithmetic — Math.round plus
 * Math.max(1, ·) keeps every derived dimension at least 1 px.
 */
export function targetSize(mode, srcW, srcH, target) {
  const fit = (n) => Math.max(1, Math.round(n));
  switch (mode) {
    case 'none':
      return { width: srcW, height: srcH };
    case 'width':
      return { width: target, height: fit((srcH / srcW) * target) };
    case 'height':
      return { width: fit((srcW / srcH) * target), height: target };
    case 'percent':
      return { width: fit((srcW * target) / 100), height: fit((srcH * target) / 100) };
    default:
      throw new Error(`unknown resize mode: ${mode}`);
  }
}

/** Watermark font size: wmScale% of the shorter output side, floor 10 px. */
export const fontSize = (w, h, wmScale = 6) =>
  Math.max(10, Math.round((Math.min(w, h) * wmScale) / 100));

/** Dark outline width for the strokeText pass: max(1, fontSize / 14). */
export const lineWidth = (fs) => Math.max(1, fs / 14);

/** Horizontal anchor: left/right pin 8 px in, center balances the text box. */
export const anchorX = (anchor, box, item) => {
  const col = anchor[1]; // l | c | r
  if (col === 'l') return MARGIN;
  if (col === 'r') return box - item - MARGIN;
  return (box - item) / 2;
};

/** Vertical anchor: top baseline fs+8, middle 1/3 fs below center, bottom h-8. */
export const anchorY = (anchor, box, fs) => {
  const row = anchor[0]; // t | m | b
  if (row === 't') return fs + MARGIN;
  if (row === 'b') return box - MARGIN;
  return box / 2 + fs / 3;
};

/** Output filename: strip the old extension, tag "-edited.webp". */
export const outName = (name) => `${name.replace(/\.[^.]+$/, '')}-edited.webp`;

/**
 * The canvas-bound half of the tool — decode, resize, watermark, encode.
 * Every layout number comes from the pure helpers above.
 */
export async function resizeAndWatermark(file, opts = {}) {
  const { mode = 'width', target = 1200, text = '', anchor = 'br', opacity = 70, wmScale = 6 } = opts;
  const bmp = await createImageBitmap(file);
  const { width: w, height: h } = targetSize(mode, bmp.width, bmp.height, target);
  const canvas = document.createElement('canvas');
  canvas.width = w;
  canvas.height = h;
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    bmp.close();
    throw new Error('canvas 2d unavailable');
  }
  ctx.imageSmoothingQuality = 'high';
  ctx.drawImage(bmp, 0, 0, w, h);
  bmp.close();

  if (text.trim() !== '') {
    const fs = fontSize(w, h, wmScale);
    ctx.font = `600 ${fs}px system-ui, sans-serif`;
    ctx.globalAlpha = opacity / 100;
    ctx.fillStyle = '#ffffff';
    ctx.strokeStyle = 'rgba(0,0,0,0.55)';
    ctx.lineWidth = lineWidth(fs);
    const x = anchorX(anchor, w, ctx.measureText(text).width);
    const y = anchorY(anchor, h, fs);
    ctx.strokeText(text, x, y); // dark outline first, white fill on top
    ctx.fillText(text, x, y);
    ctx.globalAlpha = 1;
  }

  const blob = await new Promise((resolve, reject) =>
    canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encode failed'))), 'image/webp', WEBP_QUALITY),
  );
  return { blob, name: outName(file.name), width: w, height: h };
}

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 →