Skip to content

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

// Image compressor: quality search to a size budget — C# port of the
// image-compressor tool. The search is codec-agnostic: plug your encoder in
// where the stand-in sits (System.Drawing's EncoderParameters "Quality", or
// ImageSharp's JpegEncoder.Quality for cross-platform).

using System;

static class ImageCompressor
{
    // Stand-in for canvas -> WebP/JPEG encode: encoded size at a quality.
    static long EncodeSize(double q) => 12_000 + (long)(88_000 * q);

    // Binary-search the quality until the encoded image fits the budget
    // (targetKb * 1024) — the core of the TS compressToBudget. Returns the
    // best fitting quality, or -1 when nothing fits (the TS fallback then
    // re-encodes once at the 0.05 floor).
    public static double CompressToBudget(long targetKb)
    {
        long budget = targetKb * 1024;
        double lo = 0.05, hi = 0.95, best = -1.0;
        while (lo <= hi)
        {
            double mid = (lo + hi) / 2.0;
            if (EncodeSize(mid) <= budget)
            {
                best = mid;         // fits — try a higher quality
                lo = mid + 0.05;
            }
            else
            {
                hi = mid - 0.05;    // too big — step down
            }
        }
        return best;
    }

    static void Main()
    {
        // The live tool decodes the bitmap, draws it to a canvas, then
        // searches. 50 KB budget: a mid-range quality fits just under it.
        double q = CompressToBudget(50);
        if (q < 0.0)
        {
            Console.WriteLine("no quality fits — falling back to the 0.05 floor");
            Environment.Exit(1);
        }
        Console.WriteLine($"best quality {q:F3} -> {EncodeSize(q)} bytes");
    }
}

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 →