Skip to content

Image Converter — Rust source

Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.

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

//! image-converter — convert image bytes between PNG, JPEG, and WebP.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `image-converter` tool, ported from
//! src/tools/ImageConverter.tsx.
//!
//! Codec work (PNG/JPEG/WebP encode) is environment-specific — the web tool
//! uses canvas.toBlob, which has no std equivalent — so this port keeps the
//! tool's deterministic core: format tables, output naming, quality mapping,
//! the ±size-delta badge, and the alpha flatten JPEG requires.

/// Target formats in SegmentedControl order; the tool defaults to WebP.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Format {
    Png,
    Jpeg,
    Webp,
}

pub const DEFAULT_FORMAT: Format = Format::Webp;
/// Quality slider range and default (PNG ignores the knob; it is lossless).
pub const QUALITY_MIN: u8 = 10;
pub const QUALITY_MAX: u8 = 100;
pub const DEFAULT_QUALITY: u8 = 85;

/// The tool's MIME map — canvas.toBlob's container-format argument.
pub fn mime(format: Format) -> &'static str {
    match format {
        Format::Png => "image/png",
        Format::Jpeg => "image/jpeg",
        Format::Webp => "image/webp",
    }
}

/// The tool's EXT map — download suffixes; JPEG saves as .jpg.
pub fn extension(format: Format) -> &'static str {
    match format {
        Format::Png => "png",
        Format::Jpeg => "jpg",
        Format::Webp => "webp",
    }
}

/// Snap an unknown target back to the tool's default (WebP).
pub fn resolve(value: &str) -> Format {
    match value {
        "png" => Format::Png,
        "jpeg" => Format::Jpeg,
        "webp" => Format::Webp,
        _ => DEFAULT_FORMAT,
    }
}

/// Strip the old extension (JS `name.replace(/\.[^.]+$/, '')`) and re-suffix.
/// The regex needs at least one character after the final dot, so `file.`
/// keeps its trailing dot.
pub fn output_name(name: &str, format: Format) -> String {
    let stem = match name.rfind('.') {
        Some(dot) if dot + 1 < name.len() => &name[..dot],
        _ => name,
    };
    format!("{}.{}", stem, extension(format))
}

/// Slider units (10..100) -> the 0..1 quality argument canvas.toBlob takes.
pub fn encoder_quality(quality: u8) -> f32 {
    f32::from(quality.clamp(QUALITY_MIN, QUALITY_MAX)) / 100.0
}

/// DropZone filter: only `image/*` files enter the batch.
pub fn is_image_type(media_type: &str) -> bool {
    media_type.starts_with("image/")
}

/// The ±NN% badge shown under each converted thumbnail.
pub fn size_delta_percent(original: f64, converted: f64) -> f64 {
    (converted - original) / original * 100.0
}

/// Shrinkage renders with U+2212 minus (green in the UI), growth a plus.
pub fn format_size_delta(delta_percent: f64) -> String {
    let sign = if delta_percent <= 0.0 { '−' } else { '+' };
    format!("{}{}%", sign, delta_percent.abs().round() as i64)
}

/// Flatten alpha in place over opaque white (RGBA8, tightly packed).
///
/// JPEG has no alpha channel; the browser does this by painting #fff onto
/// the canvas and then drawing the image — source-over compositing, rounded
/// per channel: `(src * a + 255 * (255 - a) + 127) / 255` — the same formula
/// the C/C++/Zig twins of this tool use.
pub fn flatten_onto_white(pixels: &mut [u8]) {
    for px in pixels.chunks_exact_mut(4) {
        let a = u32::from(px[3]);
        for c in 0..3 {
            px[c] = ((u32::from(px[c]) * a + 255 * (255 - a) + 127) / 255) as u8;
        }
        px[3] = 255;
    }
}

fn main() {
    println!("mime: {} ext: {}", mime(Format::Jpeg), extension(Format::Jpeg));
    println!("out: {}", output_name("photo.png", Format::Jpeg));
    println!("quality 85 -> {:.2}", encoder_quality(DEFAULT_QUALITY));
    println!("delta: {}", format_size_delta(size_delta_percent(2000.0, 1500.0)));

    // Two-pixel demo: half-transparent red + fully transparent blue.
    let mut pixels = vec![255, 0, 0, 128, 0, 128, 255, 0];
    flatten_onto_white(&mut pixels);
    println!("flattened rgba: {:?}", pixels);
}

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 →