Skip to content

App Icon Generator — C# 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 C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// App Icon Generator — contain-fit, centered export geometry for the
// 16/32/180/192/512 icon set.
//
// Language: C# (C# 12 / .NET 8, standard library only)
// Source:   CosmoDev polyglot showcase port, from the authored TypeScript
//           snippet src/tool-sources/app-icon-generator/typescript.ts.

namespace AppIcon;

/// <summary>One export target: the square canvas edge and the centered
/// contain-fit rect the source image is drawn into.</summary>
public readonly record struct IconRect(int Size, int X, int Y, int W, int H);

public static class AppIconGeometry
{
    public static readonly int[] DefaultSizes = [16, 32, 180, 192, 512];

    /// <summary>
    /// 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 TS pipeline feeds <c>ctx.drawImage</c> before
    /// <c>canvas.toBlob</c> PNG-encodes each square. Bitmap decode and PNG
    /// encode stay with the host.
    /// </summary>
    public static List<IconRect> IconSetPlan(int srcW, int srcH, int[]? sizes = null)
    {
        sizes ??= DefaultSizes;
        var plan = new List<IconRect>(sizes.Length);
        foreach (var px in sizes)
        {
            var scale = Math.Min((double)px / srcW, (double)px / srcH);
            // MidpointRounding.AwayFromZero matches JS Math.round (banker's
            // rounding, the C# default, would drift on exact .5 dimensions).
            int Round(double v) => (int)Math.Round(v, MidpointRounding.AwayFromZero);
            var w = Math.Max(1, Round(srcW * scale));
            var h = Math.Max(1, Round(srcH * scale));
            plan.Add(new IconRect(
                px,
                Round((px - w) / 2.0),  // letterbox on transparency
                Round((px - h) / 2.0),
                w,
                h));
        }
        return plan;
    }
}

Also available in 8 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 →