#jpeg #libjpeg #image #encoder #decoder

mozjpeg

Higher-level wrapper for Mozilla's JPEG library

14 releases

Uses new Rust 2021

0.9.4 Aug 18, 2022
0.9.3 May 23, 2022
0.9.2 Feb 13, 2022
0.9.1 Jul 21, 2021
0.8.5 May 9, 2018

#47 in Images

Download history 1524/week @ 2022-08-10 1345/week @ 2022-08-17 1499/week @ 2022-08-24 1254/week @ 2022-08-31 1153/week @ 2022-09-07 1236/week @ 2022-09-14 1090/week @ 2022-09-21 1096/week @ 2022-09-28 1284/week @ 2022-10-05 990/week @ 2022-10-12 929/week @ 2022-10-19 1036/week @ 2022-10-26 1053/week @ 2022-11-02 1319/week @ 2022-11-09 865/week @ 2022-11-16 636/week @ 2022-11-23

4,052 downloads per month
Used in 11 crates (10 directly)

IJG license

61KB
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

~5MB
~92K SLoC