#jpeg #libjpeg #image #encoder #decoder

mozjpeg

Higher-level wrapper for Mozilla’s JPEG library

23 releases

new 0.9.1 Jul 21, 2021
0.8.24 Feb 10, 2021
0.8.21 Nov 14, 2020
0.8.20 Jul 20, 2020
0.8.5 May 9, 2018

#55 in Images

Download history 540/week @ 2021-04-05 718/week @ 2021-04-12 596/week @ 2021-04-19 921/week @ 2021-04-26 558/week @ 2021-05-03 668/week @ 2021-05-10 584/week @ 2021-05-17 499/week @ 2021-05-24 477/week @ 2021-05-31 759/week @ 2021-06-07 630/week @ 2021-06-14 616/week @ 2021-06-21 732/week @ 2021-06-28 719/week @ 2021-07-05 728/week @ 2021-07-12 694/week @ 2021-07-19

2,834 downloads per month
Used in 8 crates (5 directly)

IJG license

57KB
1.5K 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(|| {
    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() {}

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

    let pixels = image.read_scanlines()?;
    assert!(image.finish_decompress());
    Ok(())
})?;

Encoding example

std::panic::catch_unwind(|| {
    let mut comp = mozjpeg::Compress::new(mozjpeg::ColorSpace::JCS_RGB);

    comp.set_size(width, height);
    comp.set_mem_dest();
    comp.start_compress();

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

    comp.finish_compress();
    let jpeg_bytes = comp.data_to_vec()?;
    // write to file, etc.
    Ok(())
})?;

Dependencies

~5.5MB
~105K SLoC