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
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! A command line image processing tool, built on top of
//! the [image] and [imageproc] crates.
//!
//! [image]: https://github.com/image-rs/image
//! [imageproc]: https://github.com/image-rs/imageproc

#![deny(missing_docs)]
#![cfg_attr(test, feature(test))]
#![allow(
    clippy::many_single_char_names,
    clippy::single_match,
    clippy::float_cmp,
    clippy::cast_lossless
)]

use image::{open, DynamicImage, GenericImageView};
use snafu::ResultExt;
use std::{
    io::{Error, ErrorKind},
    path::PathBuf,
};

pub mod documentation;
pub mod error;
use crate::error::{
    GlobIterationError, GlobPatternError, ImageCliError, ImageOpenError, ImageSaveError, Result,
};
mod example;
mod expr;
use glob::glob;
pub mod image_ops;
use image_ops::parse;
mod output_spec;
use output_spec::OutputSpec;
mod parse_utils;
mod stack;

#[cfg(test)]
extern crate test;

/// An image stack. All image operations in this library
/// operate on an image stack by popping zero or more images
/// from it, computing zero or more results and pushing those
/// back onto the stack.
pub type ImageStack = stack::Stack<DynamicImage>;

/// Load inputs, run the pipeline, and save the results.
pub fn process(
    input_patterns: &[String],
    output_patterns: &[String],
    pipeline: Option<String>,
    verbose: bool,
) -> Result<()> {
    let inputs = load_inputs(input_patterns, verbose)?;
    let output_spec = OutputSpec::parse(output_patterns)?;

    let pipeline = match pipeline {
        Some(p) => p.clone(),
        None => "".into(),
    };

    let outputs = run_pipeline(&pipeline, inputs, verbose)?;
    save_images(&output_spec, &outputs, verbose)?;

    Ok(())
}

/// Run an image processing pipeline on a stack with the given initial contents.
pub fn run_pipeline(
    pipeline: &str,
    inputs: Vec<DynamicImage>,
    verbose: bool,
) -> Result<Vec<DynamicImage>> {
    let mut stack = ImageStack::new(inputs);
    let ops = parse(pipeline)?;

    for op in ops {
        if verbose {
            println!("Applying {:?}", op);
        }
        op.apply(&mut stack);
    }

    Ok(stack.contents())
}

/// Finds the set of input paths matching the provided glob patterns.
pub fn input_paths(input_patterns: &[String]) -> Result<Vec<PathBuf>> {
    input_patterns
        .iter()
        .map(|pattern| paths_matching_pattern(pattern))
        .collect::<Result<Vec<_>>>()
        .map(|v| v.into_iter().flatten().collect())
}

/// Finds the set of paths matching the provided glob pattern.
pub fn paths_matching_pattern(pattern: &str) -> Result<Vec<PathBuf>> {
    let glob = glob(pattern).context(GlobPatternError { pattern })?;
    let paths = glob
        .map(|p| p.context(GlobIterationError))
        .collect::<Result<Vec<_>>>();

    // A bit of a hack for https://github.com/theotherphil/imagecli/issues/42
    if let Ok(p) = &paths {
        if p.len() == 0 && !pattern.contains("*") && !pattern.contains("?") {
            return Err(ImageCliError::IoError {
                context: "Input error".into(),
                source: Error::new(
                    ErrorKind::NotFound,
                    format!("No file found matching pattern '{}'", pattern),
                ),
            });
        }
    }

    paths
}

/// Load all images matching the given globs.
pub fn load_inputs(input_patterns: &[String], verbose: bool) -> Result<Vec<DynamicImage>> {
    let mut inputs = Vec::new();

    for pattern in input_patterns {
        let paths = paths_matching_pattern(pattern)?;
        if verbose {
            println!(
                "Found {} path(s) matching input pattern {}: {:?}",
                paths.len(),
                pattern,
                paths,
            );
        }

        for path in &paths {
            let image = open(&path).context(ImageOpenError { path: &path })?;
            if verbose {
                println!(
                    "Loaded input {:?} (width: {}, height: {})",
                    path,
                    image.width(),
                    image.height()
                );
            }
            inputs.push(image);
        }
    }

    Ok(inputs)
}

/// Save images according to an `OutputSpec`.
pub fn save_images(spec: &OutputSpec, images: &[DynamicImage], verbose: bool) -> Result<()> {
    for (index, image) in images.iter().enumerate() {
        match spec.nth_output_path(index) {
            Some(path) => {
                if verbose {
                    log_output(&image, &path);
                }
                image.save(&path).context(ImageSaveError { path: &path })?;
            }
            None => break,
        }
    }
    Ok(())
}

fn log_output(image: &DynamicImage, path: &str) {
    println!(
        "Output image {:?} (width: {}, height: {})",
        path,
        image.width(),
        image.height()
    );
}