Skip to content

Image Converter — JavaScript source

Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.

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

/**
 * image-converter — decode an image and re-encode it as PNG, JPEG, or WebP.
 *
 * Language: JavaScript (ES module; browsers, Node >= 18, Bun, Deno).
 * CosmoDev polyglot showcase port of the `image-converter` tool, ported from
 * src/tools/ImageConverter.tsx.
 *
 * Why this file exists: decode and encode run through browser canvas APIs
 * (createImageBitmap / canvas.toBlob) that have no portable equivalent, so
 * they stay inside one clearly marked async function. The format tables,
 * output naming, quality mapping, and size-delta badge math are pure and
 * deterministic — the parts every language twin of this tool mirrors.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

// Target formats in SegmentedControl order; the tool defaults to WebP.
export const TARGETS = ['png', 'jpeg', 'webp'];
export const DEFAULT_TARGET = 'webp';

// The tool's MIME map — canvas.toBlob's container-format argument.
export const MIME = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp' };

// The tool's EXT map — download suffixes; JPEG saves as .jpg.
export const EXT = { png: 'png', jpeg: 'jpg', webp: 'webp' };

// Quality slider range and default (PNG ignores the knob; it is lossless).
export const QUALITY_MIN = 10;
export const QUALITY_MAX = 100;
export const DEFAULT_QUALITY = 85;

/** Snap an unknown target back to the tool's default (WebP). */
export function resolveTarget(value) {
  return TARGETS.includes(value) ? value : DEFAULT_TARGET;
}

/** `name.replace(/\.[^.]+$/, '')`, then swap in the target's extension. */
export function outputName(name, target = DEFAULT_TARGET) {
  return `${name.replace(/\.[^.]+$/, '')}.${EXT[resolveTarget(target)]}`;
}

/** Slider units (10..100) -> the 0..1 quality argument canvas.toBlob takes. */
export function encoderQuality(quality = DEFAULT_QUALITY) {
  return Math.min(QUALITY_MAX, Math.max(QUALITY_MIN, Math.round(quality))) / 100;
}

/** DropZone filter: only `image/*` files enter the batch. */
export function isImageType(mediaType) {
  return typeof mediaType === 'string' && mediaType.startsWith('image/');
}

/** The ±NN% badge shown under each converted thumbnail. */
export function sizeDeltaPercent(originalSize, convertedSize) {
  return ((convertedSize - originalSize) / originalSize) * 100;
}

/** Shrinkage renders with U+2212 minus (green in the UI), growth a plus. */
export function formatSizeDelta(deltaPercent) {
  const sign = deltaPercent <= 0 ? '−' : '+';
  return `${sign}${Math.abs(deltaPercent).toFixed(0)}%`;
}

/**
 * Core pipeline — the canvas-bound part the other language twins stub out:
 * decode -> (JPEG only: paint white, then draw — the browser's source-over
 * compositing flattens alpha) -> encode via toBlob(mime, quality).
 */
export async function convertImage(file, target = DEFAULT_TARGET, quality = DEFAULT_QUALITY) {
  const t = resolveTarget(target);
  const bitmap = await createImageBitmap(file);
  try {
    const canvas = document.createElement('canvas');
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('canvas 2d context unavailable');
    if (t === 'jpeg') {
      // JPEG has no alpha channel; flatten onto white or it renders black.
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
    ctx.drawImage(bitmap, 0, 0);
    const blob = await new Promise((resolve, reject) =>
      canvas.toBlob(
        (b) => (b ? resolve(b) : reject(new Error('encode failed'))),
        MIME[t],
        encoderQuality(quality),
      ),
    );
    return { blob, name: outputName(file.name ?? 'image', t), type: MIME[t] };
  } finally {
    bitmap.close();
  }
}

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 →