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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! A crate to get images info and process them, including animated GIFs.
//!
//! Requires ImageMagick installed to function properly since some functions uses its command line
//! tools.
//!
//! # Example
//!
//! ```rust,ignore
//! extern crate image_utils;
//!
//! use std::path::Path;
//! use image_utils::{info, crop, resize};
//!
//! let path = Path::new("test.jpg");
//!
//! let inf = info(&path)?;
//! let cropped = crop(&path, 10, 10, 100, 100, &Path::new("cropped.jpg"), 5)?;
//! let resized = resize(&path, 200, 200, &Path::new("resized.jpg"), 5)?;
//!
//! println!("{:?} {:?} {:?}", inf, cropped, resized);
//! ```

#![deny(missing_docs)]

extern crate image;
extern crate gif;
extern crate wait_timeout;

use std::process::Command;
use std::error::Error;
use std::path::Path;
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::time::Duration;
use image::{GenericImage, ImageFormat, ColorType, guess_format};
use gif::Decoder;
use wait_timeout::ChildExt;

/// Common image information
#[derive(Debug, PartialEq)]
pub struct Info {
    /// Image format
    pub format: ImageFormat,
    /// Image color type
    pub color: ColorType,
    /// Width in pixels
    pub width: u32,
    /// Height in pixels
    pub height: u32,
    /// Number of frames, can be greater than 1 for animated GIFs
    pub frames: u32,
}

/// Returns common information about image
///
/// `path` - image file to analyze
///
/// Returns Info struct
pub fn info(path: &Path) -> Result<Info, Box<Error>> {
    let mut im = File::open(path)?;
    let mut buf = [0; 16];
    im.read(&mut buf)?;
    let format = guess_format(&buf)?;

    let im = image::open(path)?;
    let color = im.color();
    let (width, height) = im.dimensions();

    let frames = match format {
        ImageFormat::GIF => {
            let decoder = Decoder::new(File::open(path)?);
            let mut reader = decoder.read_info().unwrap();
            let mut frames = 0;
            while let Some(_) = reader.next_frame_info().unwrap() {
                frames += 1;
            }
            frames
        }
        _ => 1,
    };

    Ok(Info {
        format: format,
        color: color,
        width: width,
        height: height,
        frames: frames,
    })
}

/// Crops image, panics if passed coordinates or cropped image size are out of bounds of existing
/// image, fails if timeout exceeded
///
/// `src` - source image file
///
/// `x` - width offset
///
/// `y` - height offset
///
/// `width` - crop width
///
/// `height` - crop height
///
/// `dest` - destination image file
///
/// `timeout` - function timeout in seconds
///
/// Returns true on success
pub fn crop(src: &Path,
            x: u32,
            y: u32,
            width: u32,
            height: u32,
            dest: &Path,
            timeout: u32)
            -> Result<bool, Box<Error>> {
    let inf = info(src)?;

    if x + width > inf.width || y + height > inf.height {
        panic!("out of existing image bounds");
    }

    let srcs = src.to_str().unwrap();
    let dests = dest.to_str().unwrap();
    let dims = format!("{}x{}+{}+{}", width, height, x, y);

    let mut child = match inf.format {
        ImageFormat::GIF => {
            Command::new("convert").arg(srcs)
                .arg("-coalesce")
                .arg("-repage")
                .arg("0x0")
                .arg("-crop")
                .arg(dims)
                .arg("+repage")
                .arg(dests)
                .spawn()?
        }
        _ => {
            Command::new("convert").arg(srcs)
                .arg("-crop")
                .arg(dims)
                .arg(dests)
                .spawn()?
        }
    };

    let success = match child.wait_timeout(Duration::from_secs(timeout as u64))? {
        Some(status) => status.success(),
        None => {
            child.kill()?;
            child.wait()?.success()
        }
    };

    Ok(success)
}

/// Resizes image preserving its aspect ratio, fails if timeout exceeded
///
/// `src` - source image file
///
/// `width` - max width
///
/// `height` - max height
///
/// `dest` - destination image file
///
/// `timeout` - function timeout in seconds
///
/// Returns true on success
pub fn resize(src: &Path,
              width: u32,
              height: u32,
              dest: &Path,
              timeout: u32)
              -> Result<bool, Box<Error>> {
    let inf = info(src)?;

    let mut srcs = src.to_str().unwrap();
    let dests = dest.to_str().unwrap();

    let duration = Duration::from_secs(timeout as u64);

    let temp = match inf.format {
        ImageFormat::GIF => {
            let mut child = Command::new("convert").arg(srcs)
                .arg("-coalesce")
                .arg(dests)
                .spawn()?;

            srcs = dests;

            match child.wait_timeout(duration)? {
                Some(status) => status.success(),
                None => {
                    child.kill()?;
                    child.wait()?.success()
                }
            }
        }
        _ => false,
    };

    let mut child = Command::new("convert").arg("-size")
        .arg(format!("{}x{}", inf.width, inf.height))
        .arg(srcs)
        .arg("-resize")
        .arg(format!("{}x{}", width, height))
        .arg(dests)
        .spawn()?;

    let success = match child.wait_timeout(duration)? {
        Some(status) => status.success(),
        None => {
            child.kill()?;
            child.wait()?.success()
        }
    };

    if temp && !success {
        fs::remove_file(dests)?;
    }

    Ok(success)
}