jixel 0.2.10

Tiny JPEG XL encoder
Documentation
//! Losslessly transcodes a JPEG file to JPEG XL.
//!
//! The output is a JXL container whose codestream carries the JPEG's own DCT
//! coefficients, plus a `jbrd` box describing everything else about the source
//! file. Decoding it with `djxl out.jxl back.jpg` reproduces the original JPEG
//! byte for byte.
//!
//! ```text
//! cargo run --release --example jpeg_transcode -- photo.jpg photo.jxl
//! ```
//!
//! Passing `--no-reconstruct` drops the `jbrd` box. The image is still carried
//! losslessly, but only an equivalent JPEG can be produced from it, not the
//! original file.

use std::path::Path;

fn main() {
    let mut args: Vec<String> = std::env::args().skip(1).collect();
    let reconstruct = !args.iter().any(|a| a == "--no-reconstruct");
    args.retain(|a| a != "--no-reconstruct");
    if args.len() != 2 {
        eprintln!("usage: jpeg_transcode [--no-reconstruct] <input.jpg> <output.jxl>");
        std::process::exit(2);
    }
    let (input, output) = (Path::new(&args[0]), Path::new(&args[1]));

    let jpeg = match std::fs::read(input) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("could not read {}: {e}", input.display());
            std::process::exit(1);
        }
    };

    let config = jixel::JpegTranscodeConfig::default()
        .with_jpeg_reconstruction(reconstruct)
        .with_num_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
    let jxl = match jixel::encode_jpeg_lossless_with_config(&jpeg, &config) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("{e}");
            std::process::exit(1);
        }
    };

    if let Err(e) = std::fs::write(output, &jxl) {
        eprintln!("could not write {}: {e}", output.display());
        std::process::exit(1);
    }

    let saved = 100.0 - (jxl.len() as f64 / jpeg.len() as f64) * 100.0;
    println!(
        "{} bytes -> {} bytes ({saved:.1}% smaller)",
        jpeg.len(),
        jxl.len()
    );
}