1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use {
    log::{error, info},
    std::path::PathBuf,
};

pub struct WebpConverter {
    pub quality: u8,
}

impl WebpConverter {
    /// Converts the given input file to webp using ```cwebp``` and saves it to disk
    /// into the output_dir folder.
    pub fn from_png(
        &self,
        input_file_name: &PathBuf,
        output_file_name: &PathBuf,
    ) {
        if !&input_file_name.is_file() {
            error!("{} is not a file!", &input_file_name.to_str().unwrap());
            return;
        }

        if output_file_name.is_dir() {
            error!("{} is a directory!", &output_file_name.to_str().unwrap());
            return;
        };
        let o = &mut output_file_name.clone();
        o.set_extension("webp");

        let process = match std::process::Command::new("cwebp")
            .args(&[
                input_file_name.to_str().unwrap(),
                "-q",
                &self.quality.to_string(),
                "-o",
                o.to_str().unwrap(),
            ])
            .spawn()
        {
            Ok(process) => process,
            Err(err) => panic!("Running process error: {}", err),
        };

        let output = match process.wait_with_output() {
            Ok(output) => output,
            Err(err) => panic!("Retrieving output error: {}", err),
        };

        match std::string::String::from_utf8(output.stdout) {
            Ok(stdout) => info!("{}", stdout),
            Err(err) => panic!("Translating output error: {}", err),
        };
    }
}