Skip to content

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

<?php
/**
 * image-converter — convert image bytes between PNG, JPEG, and WebP.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `image-converter` tool, ported from
 * src/tools/ImageConverter.tsx.
 *
 * Image codecs are browser canvas APIs (createImageBitmap / canvas.toBlob);
 * PHP's GD is an extension rather than the standard library, so this port
 * keeps the tool's deterministic core: format tables, output naming, quality
 * mapping, the ±size-delta badge, and the JPEG alpha flatten on raw RGBA.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

const IC_TARGETS = ['png', 'jpeg', 'webp'];
const IC_DEFAULT_TARGET = 'webp';
// The tool's MIME map (canvas.toBlob's container format) and EXT map
// (download suffixes; JPEG saves as .jpg).
const IC_MIME = ['png' => 'image/png', 'jpeg' => 'image/jpeg', 'webp' => 'image/webp'];
const IC_EXT = ['png' => 'png', 'jpeg' => 'jpg', 'webp' => 'webp'];
// Quality slider range and default (PNG ignores the knob; it is lossless).
const IC_QUALITY_MIN = 10;
const IC_QUALITY_MAX = 100;
const IC_DEFAULT_QUALITY = 85;

/** Snap an unknown target back to the tool's default (WebP). */
function ic_resolve_target(string $target): string
{
    return in_array($target, IC_TARGETS, true) ? $target : IC_DEFAULT_TARGET;
}

/** The `image/<target>` string handed to canvas.toBlob in the browser. */
function ic_mime_type(string $target): string
{
    return IC_MIME[ic_resolve_target($target)];
}

/** Strip the old extension (the tool's `/\.[^.]+$/` regex) and re-suffix. */
function ic_output_name(string $name, string $target = IC_DEFAULT_TARGET): string
{
    $stem = preg_replace('/\.[^.]+$/', '', $name) ?? $name;

    return $stem . '.' . IC_EXT[ic_resolve_target($target)];
}

/** Slider units (10..100) -> the 0..1 quality argument canvas.toBlob takes. */
function ic_encoder_quality(int $quality = IC_DEFAULT_QUALITY): float
{
    return min(IC_QUALITY_MAX, max(IC_QUALITY_MIN, $quality)) / 100;
}

/** DropZone filter: only `image/*` files enter the batch. */
function ic_is_image_type(string $mediaType): bool
{
    return strpos($mediaType, 'image/') === 0; // str_starts_with is PHP 8+
}

/** The ±NN% badge shown under each converted thumbnail. */
function ic_size_delta_percent(int $originalSize, int $convertedSize): float
{
    return ($convertedSize - $originalSize) / $originalSize * 100;
}

/** Shrinkage renders with U+2212 minus (green in the UI), growth a plus. */
function ic_format_size_delta(float $deltaPercent): string
{
    $sign = $deltaPercent <= 0 ? '−' : '+';

    return $sign . round(abs($deltaPercent)) . '%';
}

/**
 * Flatten alpha in place over opaque white ($rgba is RGBA8 bytes, by
 * reference). JPEG has no alpha channel; the browser paints #fff onto the
 * canvas then draws the image — source-over, rounded per channel:
 * (src * a + 255 * (255 - a) + 127) / 255 — the C/C++/Zig twins' formula.
 */
function ic_flatten_onto_white(string &$rgba): void
{
    $len = strlen($rgba);
    for ($i = 0; $i < $len; $i += 4) {
        $a = ord($rgba[$i + 3]);
        for ($c = 0; $c < 3; $c++) {
            $rgba[$i + $c] = chr(intdiv(ord($rgba[$i + $c]) * $a + 255 * (255 - $a) + 127, 255));
        }
        $rgba[$i + 3] = chr(255);
    }
}

// Demo: flatten a 2-pixel strip (half-transparent red + transparent blue)
// and exercise the pure helpers.
if (PHP_SAPI === 'cli' && isset($argv) && realpath($argv[0]) === __FILE__) {
    $rgba = "\xFF\x00\x00\x80\x00\x80\xFF\x00";
    ic_flatten_onto_white($rgba);
    printf("%s %s %.2f\n", ic_mime_type('jpeg'), ic_output_name('photo.png', 'jpeg'), ic_encoder_quality(85));
    printf("%s\n", ic_format_size_delta(ic_size_delta_percent(2000, 1500)));
    echo bin2hex($rgba), "\n";
}

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 →