Skip to content

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

// Image compressor: quality search to a size budget — Swift port of the
// image-compressor tool. On Apple platforms the encoder is CGImageDestination
// with kCGImageDestinationLossyCompressionQuality; the binary search over
// quality is the portable part.

import Foundation

// Stand-in for canvas -> WebP/JPEG encode: encoded size at a quality.
func encodeSize(_ q: Double) -> Int { 12_000 + Int(88_000 * q) } // ~100 KB at q = 1.0

// 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 nil when nothing fits (the TS fallback then re-encodes
// once at the 0.05 floor).
func compressToBudget(targetKb: Int) -> Double? {
    let budget = targetKb * 1024
    var lo = 0.05, hi = 0.95
    var best: Double? = nil
    while lo <= hi {
        let mid = (lo + hi) / 2
        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
}

// The live tool decodes the bitmap, draws it to a canvas, then searches.
// 50 KB budget: a mid-range quality fits just under it. (main.swift:
// top-level code, no @main needed.)
if let q = compressToBudget(targetKb: 50) {
    print(String(format: "best quality %.3f -> %d bytes", q, encodeSize(q)))
} else {
    print("no quality fits — falling back to the 0.05 floor")
    exit(1)
}

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 →