day 38 @rust 画像にブラーをかけてみるんギョ。

main.rs

mod application;

use self::application::Application;

fn main() {
    let mut app = Application::new();
    app.run();
}

application.rs

use image::io::Reader as ImageReader;
use image::DynamicImage;

pub struct Application {
    source: String,
    destination: String,
    img: Option<DynamicImage>,
}

impl Application {
    pub fn new() -> Application {
        Application {
            source: String::new(),
            destination: String::new(),
            img: None, 
        }
    }

    pub fn run(&mut self) {
        self.parse_argument();
        self.load_img();
        self.process_img();
    }

    fn parse_argument(&mut self) {
        let args: Vec<String> = std::env::args().collect();
        if args.len() > 2 {
            self.source = args[1].clone();
            self.destination = args[2].clone();
        } else {
            println!("引数が不足しています。");
            std::process::exit(0);
        }
    }

    fn load_img(&mut self) {
        if !self.is_exist_src() {
            println!("ファイルが存在しません。\n現在作業しているディレクトリ からの相対パスで指定してください。");
            std::process::exit(0);
        }
        self.img = Some(ImageReader::open(&self.source).unwrap().decode().unwrap());
    }

    fn is_exist_src(&self) -> bool {
        let src = &(self.source);
        std::path::Path::new(src).exists()
    }

    fn process_img(&mut self) {
        let img = self.img.as_ref().unwrap();
        let img = img.blur(3.0);
        img.save(&self.destination);
    }
}