Skip to content

Image Compressor — PHP source

Shrink image file sizes entirely in your browser — fixed quality or an automatic fit to a size budget, optional max-dimension resize, batch support. Nothing uploads.

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

<?php
/**
 * image-compressor — re-encode images smaller, at a fixed quality or to fit a
 * size budget.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `image-compressor` tool, ported from
 * src/tools/ImageCompressor.tsx.
 *
 * The island's decode/draw/toBlob pipeline is canvas-bound, so it stays in
 * the browser; what ports is the deterministic layer around it — the
 * MIME-selection rule, the max-dimension resize math, and the binary search
 * over whole-point quality (5..95, at most seven probes). The encoder plugs
 * in as a callable; GD's imagewebp($quality) sits behind the same signature
 * in a real deployment.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** PNG sources re-encode as WebP (lossy pipeline); JPEG/WebP keep their format. */
function outputMime(string $fileType): string
{
    return $fileType === 'image/jpeg' || $fileType === 'image/webp' ? $fileType : 'image/webp';
}

/**
 * Scale a source size down so no side exceeds $maxDim, never up (0 keeps the
 * original size). Returns [width, height]; each side is clamped at 1 px like
 * the live canvas code, and round() is half-away-from-zero, matching JS
 * Math.round on positive sizes.
 */
function targetDimensions(int $width, int $height, int $maxDim): array
{
    $scale = $maxDim > 0 ? min(1.0, $maxDim / max($width, $height)) : 1.0;

    return [
        max(1, (int) round($width * $scale)),
        max(1, (int) round($height * $scale)),
    ];
}

/**
 * Binary-search the canvas quality (5..95) until the encoded size fits the
 * budget ($targetKb * 1024) — the core of the island's target mode. Quality
 * moves in whole points, $mid = intdiv($lo + $hi, 2), and the loop runs at
 * most seven times — enough to settle 5..95. Returns the best fitting
 * quality, or null when nothing fits (the island then re-encodes once at the
 * 5-point floor).
 */
function compressToBudget(callable $encodeSize, int $targetKb): ?int
{
    $budget = $targetKb * 1024;
    $lo = 5;
    $hi = 95;
    $best = null;
    for ($step = 0; $step < 7 && $lo <= $hi; $step++) {
        $mid = intdiv($lo + $hi, 2);
        if ($encodeSize($mid / 100) <= $budget) {
            $best = $mid; // fits — try higher quality
            $lo = $mid + 1;
        } else {
            $hi = $mid - 1; // too big — step down
        }
    }

    return $best;
}

// Deterministic stand-in codec: size grows ~linearly with quality
// (~100 KB at q = 1.0), standing in for canvas.toBlob blob sizes.
$fakeEncodeSize = static fn (float $q): int => (int) (12000.0 + 88000.0 * $q);

// The live tool decodes the bitmap, draws it to a canvas, then searches.
// 50 KB budget: a mid-range quality fits just under it.
$q = compressToBudget($fakeEncodeSize, 50);
if ($q === null) {
    echo "no quality fits — falling back to the 5-point floor\n";
    exit(1);
}
printf("best quality %d -> %d bytes\n", $q, $fakeEncodeSize($q / 100));

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 →