Search code examples
imagerustwebp

Rust with optional webp-encoding feature


I'm trying to include the sept 10,2022 addition of a webp encoder in my image processing tool

so my cargo.toml file has the added feature

   image = {version =  "0.24.6", features = ["webp-encoder"]}

And use it as such

   let fout = &mut BufWriter::new(File::create(path)?);

    webp::WebPEncoder::new(fout).write_image(buf, width, height, color),

where buf is image.as_bytes().

It bails with the following:

Err(Unsupported(UnsupportedError { format: Exact(WebP), kind: Color(L8) }))

Anyone use this newish encoder.


Solution

  • As per the documentation WebPEncoder supports encoding for ColorType::Rgb8 and ColorType::Rgba8 only:

    Format Encoding
    WebP Rgb8, Rgba8

    So you'll need to use one of those instead of ColorType::L8. Of course if your image isn't in Rgb8 / Rgba8 already you have to convert it first, as far as I know you have to go through DynamicImage:

    use std::io::BufWriter;
    
    use image::{codecs::webp, ColorType, DynamicImage, EncodableLayout, ImageEncoder};
    
    fn main() {
        // should work with any image type really, not just `GrayImage`.
        let gray_image = image::GrayImage::new(10, 20);
        let rgb_image = DynamicImage::from(gray_image).into_rgb8();
        let buf = rgb_image.as_bytes();
        let f_out = &mut BufWriter::new(Vec::new());
        webp::WebPEncoder::new(f_out)
            .write_image(buf, 10, 20, ColorType::Rgb8)
            .unwrap();
    }