1 //! Image Processing Functions
2 use std::cmp;
3 
4 use num_traits::{NumCast};
5 
6 use crate::image::{GenericImage, GenericImageView, SubImage};
7 use crate::traits::{Lerp, Primitive, Pixel};
8 
9 pub use self::sample::FilterType;
10 
11 pub use self::sample::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle};
12 
13 /// Affine transformations
14 pub use self::affine::{
15     flip_horizontal, flip_horizontal_in_place, flip_vertical, flip_vertical_in_place, rotate180,
16     rotate180_in_place, rotate270, rotate90, rotate180_in, rotate90_in, rotate270_in, flip_horizontal_in, flip_vertical_in
17 };
18 
19 /// Image sampling
20 pub use self::sample::{blur, filter3x3, resize, thumbnail, unsharpen};
21 
22 /// Color operations
23 pub use self::colorops::{brighten, contrast, dither, grayscale, huerotate, index_colors, invert,
24                          BiLevel, ColorMap};
25 
26 mod affine;
27 // Public only because of Rust bug:
28 // https://github.com/rust-lang/rust/issues/18241
29 pub mod colorops;
30 mod sample;
31 
32 /// Return a mutable view into an image
crop<I: GenericImageView>( image: &mut I, x: u32, y: u32, width: u32, height: u32, ) -> SubImage<&mut I>33 pub fn crop<I: GenericImageView>(
34     image: &mut I,
35     x: u32,
36     y: u32,
37     width: u32,
38     height: u32,
39 ) -> SubImage<&mut I> {
40     let (x, y, width, height) = crop_dimms(image, x, y, width, height);
41     SubImage::new(image, x, y, width, height)
42 }
43 
44 /// Return an immutable view into an image
crop_imm<I: GenericImageView>( image: &I, x: u32, y: u32, width: u32, height: u32, ) -> SubImage<&I>45 pub fn crop_imm<I: GenericImageView>(
46     image: &I,
47     x: u32,
48     y: u32,
49     width: u32,
50     height: u32,
51 ) -> SubImage<&I> {
52     let (x, y, width, height) = crop_dimms(image, x, y, width, height);
53     SubImage::new(image, x, y, width, height)
54 }
55 
crop_dimms<I: GenericImageView>( image: &I, x: u32, y: u32, width: u32, height: u32, ) -> (u32, u32, u32, u32)56 fn crop_dimms<I: GenericImageView>(
57     image: &I,
58     x: u32,
59     y: u32,
60     width: u32,
61     height: u32,
62 ) -> (u32, u32, u32, u32) {
63     let (iwidth, iheight) = image.dimensions();
64 
65     let x = cmp::min(x, iwidth);
66     let y = cmp::min(y, iheight);
67 
68     let height = cmp::min(height, iheight - y);
69     let width = cmp::min(width, iwidth - x);
70 
71     (x, y, width, height)
72 }
73 
74 /// Calculate the region that can be copied from top to bottom.
75 ///
76 /// Given image size of bottom and top image, and a point at which we want to place the top image
77 /// onto the bottom image, how large can we be? Have to wary of the following issues:
78 /// * Top might be larger than bottom
79 /// * Overflows in the computation
80 /// * Coordinates could be completely out of bounds
81 ///
82 /// The main idea is to make use of inequalities provided by the nature of `saturing_add` and
83 /// `saturating_sub`. These intrinsically validate that all resulting coordinates will be in bounds
84 /// for both images.
85 ///
86 /// We want that all these coordinate accesses are safe:
87 /// 1. `bottom.get_pixel(x + [0..x_range), y + [0..y_range))`
88 /// 2. `top.get_pixel([0..x_range), [0..y_range))`
89 ///
90 /// Proof that the function provides the necessary bounds for width. Note that all unaugmented math
91 /// operations are to be read in standard arithmetic, not integer arithmetic. Since no direct
92 /// integer arithmetic occurs in the implementation, this is unambiguous.
93 ///
94 /// ```text
95 /// Three short notes/lemmata:
96 /// - Iff `(a - b) <= 0` then `a.saturating_sub(b) = 0`
97 /// - Iff `(a - b) >= 0` then `a.saturating_sub(b) = a - b`
98 /// - If  `a <= c` then `a.saturating_sub(b) <= c.saturating_sub(b)`
99 ///
100 /// 1.1 We show that if `bottom_width <= x`, then `x_range = 0` therefore `x + [0..x_range)` is empty.
101 ///
102 /// x_range
103 ///  = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x)
104 /// <= bottom_width.saturating_sub(x)
105 ///
106 /// bottom_width <= x
107 /// <==> bottom_width - x <= 0
108 /// <==> bottom_width.saturating_sub(x) = 0
109 ///  ==> x_range <= 0
110 ///  ==> x_range  = 0
111 ///
112 /// 1.2 If `x < bottom_width` then `x + x_range < bottom_width`
113 ///
114 /// x + x_range
115 /// <= x + bottom_width.saturating_sub(x)
116 ///  = x + (bottom_width - x)
117 ///  = bottom_width
118 ///
119 /// 2. We show that `x_range <= top_width`
120 ///
121 /// x_range
122 ///  = (top_width.saturating_add(x).min(bottom_width)).saturating_sub(x)
123 /// <= top_width.saturating_add(x).saturating_sub(x)
124 /// <= (top_wdith + x).saturating_sub(x)
125 ///  = top_width (due to `top_width >= 0` and `x >= 0`)
126 /// ```
127 ///
128 /// Proof is the same for height.
overlay_bounds( (bottom_width, bottom_height): (u32, u32), (top_width, top_height): (u32, u32), x: u32, y: u32 ) -> (u32, u32)129 pub fn overlay_bounds(
130     (bottom_width, bottom_height): (u32, u32),
131     (top_width, top_height): (u32, u32),
132     x: u32,
133     y: u32
134 )
135     -> (u32, u32)
136 {
137     let x_range = top_width.saturating_add(x) // Calculate max coordinate
138         .min(bottom_width) // Restrict to lower width
139         .saturating_sub(x); // Determinate length from start `x`
140     let y_range = top_height.saturating_add(y)
141         .min(bottom_height)
142         .saturating_sub(y);
143     (x_range, y_range)
144 }
145 
146 /// Overlay an image at a given coordinate (x, y)
overlay<I, J>(bottom: &mut I, top: &J, x: u32, y: u32) where I: GenericImage, J: GenericImageView<Pixel = I::Pixel>,147 pub fn overlay<I, J>(bottom: &mut I, top: &J, x: u32, y: u32)
148 where
149     I: GenericImage,
150     J: GenericImageView<Pixel = I::Pixel>,
151 {
152     let bottom_dims = bottom.dimensions();
153     let top_dims = top.dimensions();
154 
155     // Crop our top image if we're going out of bounds
156     let (range_width, range_height) = overlay_bounds(bottom_dims, top_dims, x, y);
157 
158     for top_y in 0..range_height {
159         for top_x in 0..range_width {
160             let p = top.get_pixel(top_x, top_y);
161             let mut bottom_pixel = bottom.get_pixel(x + top_x, y + top_y);
162             bottom_pixel.blend(&p);
163 
164             bottom.put_pixel(x + top_x, y + top_y, bottom_pixel);
165         }
166     }
167 }
168 
169 /// Tile an image by repeating it multiple times
170 ///
171 /// # Examples
172 /// ```no_run
173 /// use image::{RgbaImage};
174 ///
175 /// fn main() {
176 ///      let mut img = RgbaImage::new(1920, 1080);
177 ///      let tile = image::open("tile.png").unwrap();
178 ///
179 ///      image::imageops::tile(&mut img, &tile);
180 ///      img.save("tiled_wallpaper.png").unwrap();
181 /// }
182 /// ```
tile<I, J>(bottom: &mut I, top: &J) where I: GenericImage, J: GenericImageView<Pixel = I::Pixel>,183 pub fn tile<I, J>(bottom: &mut I, top: &J)
184 where
185     I: GenericImage,
186     J: GenericImageView<Pixel = I::Pixel>,
187 {
188     for x in (0..bottom.width()).step_by(top.width() as usize) {
189         for y in (0..bottom.height()).step_by(top.height() as usize) {
190             overlay(bottom, top, x, y);
191         }
192     }
193 }
194 
195 /// Fill the image with a linear vertical gradient
196 ///
197 /// This function assumes a linear color space.
198 ///
199 /// # Examples
200 /// ```no_run
201 /// use image::{Rgba, RgbaImage, Pixel};
202 ///
203 /// fn main() {
204 ///     let mut img = RgbaImage::new(100, 100);
205 ///     let start = Rgba::from_slice(&[0, 128, 0, 0]);
206 ///     let end = Rgba::from_slice(&[255, 255, 255, 255]);
207 ///
208 ///     image::imageops::vertical_gradient(&mut img, start, end);
209 ///     img.save("vertical_gradient.png").unwrap();
210 /// }
vertical_gradient<S, P, I>(img: &mut I, start: &P, stop: &P) where I: GenericImage<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + Lerp + 'static211 pub fn vertical_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
212 where
213     I: GenericImage<Pixel = P>,
214     P: Pixel<Subpixel = S> + 'static,
215     S: Primitive + Lerp + 'static
216 {
217     for y in 0..img.height() {
218         let pixel = start.map2(stop, |a, b| {
219             let y = <S::Ratio as NumCast>::from(y).unwrap();
220             let height = <S::Ratio as NumCast>::from(img.height() - 1).unwrap();
221             S::lerp(a, b, y / height)
222         });
223 
224         for x in 0..img.width() {
225             img.put_pixel(x, y, pixel);
226         }
227     }
228 }
229 
230 /// Fill the image with a linear horizontal gradient
231 ///
232 /// This function assumes a linear color space.
233 ///
234 /// # Examples
235 /// ```no_run
236 /// use image::{Rgba, RgbaImage, Pixel};
237 ///
238 /// fn main() {
239 ///     let mut img = RgbaImage::new(100, 100);
240 ///     let start = Rgba::from_slice(&[0, 128, 0, 0]);
241 ///     let end = Rgba::from_slice(&[255, 255, 255, 255]);
242 ///
243 ///     image::imageops::horizontal_gradient(&mut img, start, end);
244 ///     img.save("horizontal_gradient.png").unwrap();
245 /// }
horizontal_gradient<S, P, I>(img: &mut I, start: &P, stop: &P) where I: GenericImage<Pixel = P>, P: Pixel<Subpixel = S> + 'static, S: Primitive + Lerp + 'static246 pub fn horizontal_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
247 where
248     I: GenericImage<Pixel = P>,
249     P: Pixel<Subpixel = S> + 'static,
250     S: Primitive + Lerp + 'static
251 {
252     for x in 0..img.width() {
253         let pixel = start.map2(stop, |a, b| {
254             let x = <S::Ratio as NumCast>::from(x).unwrap();
255             let width = <S::Ratio as NumCast>::from(img.width() - 1).unwrap();
256             S::lerp(a, b, x / width)
257         });
258 
259         for y in 0..img.height() {
260             img.put_pixel(x, y, pixel);
261         }
262     }
263 }
264 
265 /// Replace the contents of an image at a given coordinate (x, y)
replace<I, J>(bottom: &mut I, top: &J, x: u32, y: u32) where I: GenericImage, J: GenericImageView<Pixel = I::Pixel>,266 pub fn replace<I, J>(bottom: &mut I, top: &J, x: u32, y: u32)
267 where
268     I: GenericImage,
269     J: GenericImageView<Pixel = I::Pixel>,
270 {
271     let bottom_dims = bottom.dimensions();
272     let top_dims = top.dimensions();
273 
274     // Crop our top image if we're going out of bounds
275     let (range_width, range_height) = overlay_bounds(bottom_dims, top_dims, x, y);
276 
277     for top_y in 0..range_height {
278         for top_x in 0..range_width {
279             let p = top.get_pixel(top_x, top_y);
280             bottom.put_pixel(x + top_x, y + top_y, p);
281         }
282     }
283 }
284 
285 #[cfg(test)]
286 mod tests {
287 
288     use super::overlay;
289     use crate::RgbaImage;
290     use crate::ImageBuffer;
291     use crate::color::Rgb;
292 
293     #[test]
294     /// Test that images written into other images works
test_image_in_image()295     fn test_image_in_image() {
296         let mut target = ImageBuffer::new(32, 32);
297         let source = ImageBuffer::from_pixel(16, 16, Rgb([255u8, 0, 0]));
298         overlay(&mut target, &source, 0, 0);
299         assert!(*target.get_pixel(0, 0) == Rgb([255u8, 0, 0]));
300         assert!(*target.get_pixel(15, 0) == Rgb([255u8, 0, 0]));
301         assert!(*target.get_pixel(16, 0) == Rgb([0u8, 0, 0]));
302         assert!(*target.get_pixel(0, 15) == Rgb([255u8, 0, 0]));
303         assert!(*target.get_pixel(0, 16) == Rgb([0u8, 0, 0]));
304     }
305 
306     #[test]
307     /// Test that images written outside of a frame doesn't blow up
test_image_in_image_outside_of_bounds()308     fn test_image_in_image_outside_of_bounds() {
309         let mut target = ImageBuffer::new(32, 32);
310         let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
311         overlay(&mut target, &source, 1, 1);
312         assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
313         assert!(*target.get_pixel(1, 1) == Rgb([255u8, 0, 0]));
314         assert!(*target.get_pixel(31, 31) == Rgb([255u8, 0, 0]));
315     }
316 
317     #[test]
318     /// Test that images written to coordinates out of the frame doesn't blow up
319     /// (issue came up in #848)
test_image_outside_image_no_wrap_around()320     fn test_image_outside_image_no_wrap_around() {
321         let mut target = ImageBuffer::new(32, 32);
322         let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
323         overlay(&mut target, &source, 33, 33);
324         assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
325         assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
326         assert!(*target.get_pixel(31, 31) == Rgb([0, 0, 0]));
327     }
328 
329     #[test]
330     /// Test that images written to coordinates with overflow works
test_image_coordinate_overflow()331     fn test_image_coordinate_overflow() {
332         let mut target = ImageBuffer::new(16, 16);
333         let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
334         // Overflows to 'sane' coordinates but top is larger than bot.
335         overlay(&mut target, &source, u32::max_value() - 31, u32::max_value() - 31);
336         assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
337         assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
338         assert!(*target.get_pixel(15, 15) == Rgb([0, 0, 0]));
339     }
340 
341     use super::{horizontal_gradient, vertical_gradient};
342 
343     #[test]
344     /// Test that horizontal gradients are correctly generated
test_image_horizontal_gradient_limits()345     fn test_image_horizontal_gradient_limits() {
346         let mut img = ImageBuffer::new(100, 1);
347 
348         let start = Rgb([0u8, 128, 0]);
349         let end = Rgb([255u8, 255, 255]);
350 
351         horizontal_gradient(&mut img, &start, &end);
352 
353         assert_eq!(img.get_pixel(0, 0), &start);
354         assert_eq!(img.get_pixel(img.width() - 1, 0), &end);
355     }
356 
357     #[test]
358     /// Test that vertical gradients are correctly generated
test_image_vertical_gradient_limits()359     fn test_image_vertical_gradient_limits() {
360         let mut img = ImageBuffer::new(1, 100);
361 
362         let start = Rgb([0u8, 128, 0]);
363         let end = Rgb([255u8, 255, 255]);
364 
365         vertical_gradient(&mut img, &start, &end);
366 
367         assert_eq!(img.get_pixel(0, 0), &start);
368         assert_eq!(img.get_pixel(0, img.height() - 1), &end);
369     }
370 
371     #[test]
372     /// Test blur doens't panick when passed 0.0
test_blur_zero()373     fn test_blur_zero() {
374         let image = RgbaImage::new(50, 50);
375         let _ = super::blur(&image, 0.0);
376     }
377 }
378