Skip to content

App Icon Generator — PHP source

Turn one image into the full web app icon set — favicon, apple-touch-icon and manifest sizes as crisp PNGs. Letterboxed contain-fit, optional white background — runs entirely in your browser.

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

<?php
/**
 * app-icon-generator — contain-fit, centered export geometry for the
 * 16/32/180/192/512 web icon set.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `app-icon-generator` tool, ported
 * from src/tools/AppIconGenerator.tsx.
 *
 * The island's interactive half — createImageBitmap decode, canvas drawImage,
 * canvas.toBlob PNG encode — is browser-bound and stays there; this file ports
 * the deterministic geometry that decides where the source image lands on
 * every square canvas. PHP's round() rounds half away from zero, which matches
 * JS Math.round on the all-positive values this geometry produces.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** The standard size set every web app is asked for (the island's SIZES). */
const AIG_DEFAULT_SIZES = [16, 32, 180, 192, 512];

/**
 * One export target: the square canvas edge and the centered contain-fit
 * rect the source image is drawn into.
 */
final class IconRect
{
    public function __construct(
        public int $size, // canvas edge (px × px) this rect was fitted into
        public int $x,    // top-left offset: centers the fitted image
        public int $y,
        public int $w,    // fitted image size, at least 1×1
        public int $h
    ) {
    }
}

/**
 * The deterministic half of the tool: per export size, the contain-fit rect
 * (scale = min(px/w, px/h), clamped to >= 1) plus the centered draw offset —
 * the geometry the island feeds ctx.drawImage before canvas.toBlob PNG-encodes
 * each square. Bitmap decode and PNG encode stay with the host.
 *
 * @param int|null $sizes Export sizes; defaults to AIG_DEFAULT_SIZES.
 * @return IconRect[]
 */
function icon_set_plan(int $src_w, int $src_h, ?array $sizes = null): array
{
    $sizes ??= AIG_DEFAULT_SIZES;
    $plan = [];
    foreach ($sizes as $px) {
        $scale = min($px / $src_w, $px / $src_h);
        // (int) after round() is safe: round() already returned a whole number.
        $w = max(1, (int) round($src_w * $scale));
        $h = max(1, (int) round($src_h * $scale));
        $plan[] = new IconRect(
            $px,
            (int) round(($px - $w) / 2), // letterbox on transparency
            (int) round(($px - $h) / 2),
            $w,
            $h
        );
    }
    return $plan;
}

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 →