9 releases

0.10.10 Sep 7, 2024
0.10.9 Jul 7, 2024
0.10.7 Mar 5, 2024
0.10.5 Oct 3, 2023
0.8.5 May 9, 2018

#198 in Images

Download history 3270/week @ 2024-07-18 3560/week @ 2024-07-25 4355/week @ 2024-08-01 3419/week @ 2024-08-08 2657/week @ 2024-08-15 2246/week @ 2024-08-22 2711/week @ 2024-08-29 3135/week @ 2024-09-05 3204/week @ 2024-09-12 2852/week @ 2024-09-19 3188/week @ 2024-09-26 2854/week @ 2024-10-03 2410/week @ 2024-10-10 2366/week @ 2024-10-17 1931/week @ 2024-10-24 1764/week @ 2024-10-31

9,008 downloads per month
Used in 21 crates (13 directly)

IJG license

85KB
2K SLoC

Rust wrapper for MozJPEG library

This library adds a safe(r) interface on top of libjpeg-turbo and MozJPEG for reading and writing well-compressed JPEG images.

The interface is still being developed, so it has rough edges and may change.

In particular, error handling is weird due to libjpeg's peculiar design. Error handling can't use Result, but needs to depend on Rust's resume_unwind (a panic, basically) to signal any errors in libjpeg. It's necessary to wrap all uses of this library in catch_unwind.

In crates compiled with panic=abort setting, any JPEG error will abort the process.

Decoding example

std::panic::catch_unwind(|| -> std::io::Result<Vec<rgb::Rgb::<u8>>> {
    let d = mozjpeg::Decompress::with_markers(mozjpeg::ALL_MARKERS)
        .from_path("tests/test.jpg")?;

    d.width(); // FYI
    d.height();
    d.color_space() == mozjpeg::ColorSpace::JCS_YCbCr;
    for marker in d.markers() { /* read metadata or color profiles */ }

    // rgb() enables conversion
    let mut image = d.rgb()?;
    image.width();
    image.height();
    image.color_space() == mozjpeg::ColorSpace::JCS_RGB;

    let pixels = image.read_scanlines()?;
    image.finish()?;
    Ok(pixels)
});

Encoding example

# let width = 8; let height = 8;
std::panic::catch_unwind(|| -> std::io::Result<Vec<u8>> {
    let mut comp = mozjpeg::Compress::new(mozjpeg::ColorSpace::JCS_RGB);

    comp.set_size(width, height);
    let mut comp = comp.start_compress(Vec::new())?; // any io::Write will work

    // replace with your image data
    let pixels = vec![0u8; width * height * 3];
    comp.write_scanlines(&pixels[..])?;

    let writer = comp.finish()?;
    Ok(writer)
});

Dependencies

~5MB
~98K SLoC