Skip to content

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

//! image-compressor — re-encode images smaller, at a fixed quality or to fit
//! a size budget.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `image-compressor` tool, ported from
//! src/tools/ImageCompressor.tsx.
//!
//! The island's decode/draw/toBlob pipeline is canvas-bound, so it stays in
//! the browser; what ports is the deterministic layer around it — the
//! MIME-selection rule, the max-dimension resize math, and the binary search
//! over whole-point quality (5..=95, at most seven probes) for the largest
//! quality whose encoded size fits a byte budget. Std has no image codec, so
//! the encoder plugs in as a `f64 -> u64` size function (image/webp or
//! libwebp sits behind that signature in a real build).
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// PNG sources re-encode as WebP (lossy pipeline); JPEG/WebP keep their format.
pub fn output_mime(file_type: &str) -> &str {
    match file_type {
        "image/jpeg" | "image/webp" => file_type,
        _ => "image/webp",
    }
}

/// Scale a source size down so no side exceeds `max_dim`, never up (0 keeps
/// the original size). Each side is clamped at 1 px and rounded half-up, like
/// the island's `Math.max(1, Math.round(...))` on the canvas dimensions.
pub fn target_dimensions(width: u32, height: u32, max_dim: u32) -> (u32, u32) {
    let scale = if max_dim > 0 {
        (max_dim as f64 / width.max(height) as f64).min(1.0)
    } else {
        1.0
    };
    let px = |v: u32| ((v as f64 * scale + 0.5).floor() as u32).max(1);
    (px(width), px(height))
}

/// Binary-search the canvas quality (5..=95) until the encoded size fits the
/// budget (`target_kb * 1024`) — the core of the island's target mode.
/// Quality moves in whole points, `mid = (lo + hi) / 2`, and the loop runs at
/// most seven times — enough to settle 5..=95. Returns the best fitting
/// quality, or `None` when nothing fits (the island then re-encodes once at
/// the 5-point floor).
pub fn compress_to_budget(encode_size: &dyn Fn(f64) -> u64, target_kb: u64) -> Option<u32> {
    let budget = target_kb * 1024;
    let (mut lo, mut hi) = (5u32, 95u32);
    let mut best = None;
    for _ in 0..7 {
        if lo > hi {
            break;
        }
        let mid = (lo + hi) / 2;
        if encode_size(mid as f64 / 100.0) <= budget {
            best = Some(mid); // fits — try higher quality
            lo = mid + 1;
        } else {
            hi = mid - 1; // too big — step down
        }
    }
    best
}

/// Deterministic stand-in codec: size grows ~linearly with quality
/// (~100 KB at q = 1.0), standing in for canvas.toBlob blob sizes.
fn fake_encode(q: f64) -> u64 {
    (12_000.0 + 88_000.0 * q) as u64
}

fn 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.
    match compress_to_budget(&fake_encode, 50) {
        Some(q) => println!("best quality {} -> {} bytes", q, fake_encode(q as f64 / 100.0)),
        None => println!("no quality fits — falling back to the 5-point floor"),
    }
}

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 →