Skip to main content

decode_with

Function decode_with 

Source
pub fn decode_with(bytes: &[u8], options: &DecodeOptions) -> Result<Image>
Expand description

Decode a JPEG 2000 codestream or JP2 file like decode, governed by options.

Every DecodeOptions field is set with a with_* method. This reads a JP2 file at half size and converts it to sRGB:

use rust_j2k::{ColorOutput, DecodeOptions, Error, decode_with};

let bytes = std::fs::read("image.jp2")?;
let options = DecodeOptions::default()
    .with_resolution_reduction(1)
    .with_color(ColorOutput::Srgb);
match decode_with(&bytes, &options) {
    Ok(image) => {
        // For a 16x12 file, one level discarded halves each side.
        assert_eq!((image.width, image.height), (8, 6));
        // Red, green, blue and opacity.
        assert_eq!(image.components.len(), 4);
    }
    // Options that contradict each other or do not fit the file (a
    // reduction past its levels, `raw_channels` with sRGB output), or a
    // file the conversion cannot handle (`Unsupported`), are handled
    // here in real code. This file is fine, so they fail the example.
    Err(Error::InvalidOptions(why) | Error::Unsupported(why)) => panic!("{why}"),
    Err(e) => panic!("decode failed: {e}"),
}

Failures are the same Error variants as decode, plus Error::InvalidOptions for options that are invalid on their own (WorkLimit::Raised(0), a max_quality_layers of Some(0)), contradict each other, or do not fit the file.