Search code examples
rustrust-crates

Using "image" from crates.io to make an image into a grayscale version of itself


use wasm_bindgen::prelude::wasm_bindgen;
use web_sys::console::log_1 as log;
use base64::{Engine as _, engine::{general_purpose}};
use image::{load_from_memory, imageops};




#[wasm_bindgen]
pub fn grayscaleImg(encoded_file: &str) {

    log(&"Grayscale called".into());

    let base64_to_vector = general_purpose::STANDARD.decode(encoded_file).unwrap();
    log(&"Image decoded".into());

    let img = load_from_memory(&base64_to_vector);
    log(&"Image Loaded".into());
    
    let gray_img = imageops::grayscale(img);
    log(&"Grayscale effect applied".into());

}
error[E0277]: the trait bound `Result<DynamicImage, ImageError>: GenericImageView` is not satisfied
  --> src\lib.rs:21:20
   |
21 |     let gray_img = imageops::grayscale(&img);
   |                    ^^^^^^^^^^^^^^^^^^^ the trait `GenericImageView` is not implemented for `Result<DynamicImage, ImageError>`
   |
   = help: the following other types implement trait `GenericImageView`:
             DynamicImage
             ImageBuffer<P, Container>
             View<Buffer, P>
             ViewMut<Buffer, P>
             image::image::SubImageInner<I>

i am trying to use the imageops::grayscale to make an image into a grayscale version of itself, the image comes from posting an image to a website however i keep getting different errors even though it seems as though im using the crate correctly the error says


Solution

  • image::load_from_memory() returns a Result<DynamicImage, ImageError>, but image::imageops::grayscale() requires a DynamicImage.

    You can either unwrap() the returned Result type, which means your program will crash if the returned value is an error, or you can handle the error using a match statement.

    Here is how to do it using unwrap():

    pub fn grayscaleImg(encoded_file: &str) {
        let base64_to_vector = general_purpose::STANDARD.decode(encoded_file).unwrap();
        let img = load_from_memory(&base64_to_vector).unwrap();
        let gray_img = imageops::grayscale(&img);
    }
    

    And here is how to do it using match:

    pub fn grayscaleImg(encoded_file: &str) {
        let base64_to_vector = general_purpose::STANDARD.decode(encoded_file).unwrap();
        let img = match load_from_memory(&base64_to_vector) {
            Ok(img) => img,
            Err(error) => {
                // Handle error here.
            }
        };
        let gray_img = imageops::grayscale(&img);
    }