1use std::cmp;
3
4use crate::image::{GenericImage, GenericImageView, SubImage};
5use crate::traits::{Lerp, Pixel, Primitive};
6
7pub use self::sample::FilterType;
8
9pub use self::sample::FilterType::{CatmullRom, Gaussian, Lanczos3, Nearest, Triangle};
10
11pub use self::affine::{
13    flip_horizontal, flip_horizontal_in, flip_horizontal_in_place, flip_vertical, flip_vertical_in,
14    flip_vertical_in_place, rotate180, rotate180_in, rotate180_in_place, rotate270, rotate270_in,
15    rotate90, rotate90_in,
16};
17
18pub use self::sample::{
20    blur, filter3x3, interpolate_bilinear, interpolate_nearest, resize, sample_bilinear,
21    sample_nearest, thumbnail, unsharpen,
22};
23
24pub use self::colorops::{
26    brighten, contrast, dither, grayscale, grayscale_alpha, grayscale_with_type,
27    grayscale_with_type_alpha, huerotate, index_colors, invert, BiLevel, ColorMap,
28};
29
30mod affine;
31pub mod colorops;
34mod fast_blur;
35mod sample;
36
37pub use fast_blur::fast_blur;
38
39pub fn crop<I: GenericImageView>(
42    image: &mut I,
43    x: u32,
44    y: u32,
45    width: u32,
46    height: u32,
47) -> SubImage<&mut I> {
48    let (x, y, width, height) = crop_dimms(image, x, y, width, height);
49    SubImage::new(image, x, y, width, height)
50}
51
52pub fn crop_imm<I: GenericImageView>(
55    image: &I,
56    x: u32,
57    y: u32,
58    width: u32,
59    height: u32,
60) -> SubImage<&I> {
61    let (x, y, width, height) = crop_dimms(image, x, y, width, height);
62    SubImage::new(image, x, y, width, height)
63}
64
65fn crop_dimms<I: GenericImageView>(
66    image: &I,
67    x: u32,
68    y: u32,
69    width: u32,
70    height: u32,
71) -> (u32, u32, u32, u32) {
72    let (iwidth, iheight) = image.dimensions();
73
74    let x = cmp::min(x, iwidth);
75    let y = cmp::min(y, iheight);
76
77    let height = cmp::min(height, iheight - y);
78    let width = cmp::min(width, iwidth - x);
79
80    (x, y, width, height)
81}
82
83#[must_use]
139pub fn overlay_bounds(
140    (bottom_width, bottom_height): (u32, u32),
141    (top_width, top_height): (u32, u32),
142    x: u32,
143    y: u32,
144) -> (u32, u32) {
145    let x_range = top_width
146        .saturating_add(x) .min(bottom_width) .saturating_sub(x); let y_range = top_height
150        .saturating_add(y)
151        .min(bottom_height)
152        .saturating_sub(y);
153    (x_range, y_range)
154}
155
156fn overlay_bounds_ext(
173    (bottom_width, bottom_height): (u32, u32),
174    (top_width, top_height): (u32, u32),
175    x: i64,
176    y: i64,
177) -> (u32, u32, u32, u32, u32, u32) {
178    if x > i64::from(bottom_width)
180        || y > i64::from(bottom_height)
181        || x.saturating_add(i64::from(top_width)) <= 0
182        || y.saturating_add(i64::from(top_height)) <= 0
183    {
184        return (0, 0, 0, 0, 0, 0);
185    }
186
187    let max_x = x.saturating_add(i64::from(top_width));
189    let max_y = y.saturating_add(i64::from(top_height));
190
191    let max_inbounds_x = max_x.clamp(0, i64::from(bottom_width)) as u32;
195    let max_inbounds_y = max_y.clamp(0, i64::from(bottom_height)) as u32;
196    let origin_bottom_x = x.clamp(0, i64::from(bottom_width)) as u32;
197    let origin_bottom_y = y.clamp(0, i64::from(bottom_height)) as u32;
198
199    let x_range = max_inbounds_x - origin_bottom_x;
204    let y_range = max_inbounds_y - origin_bottom_y;
205
206    let origin_top_x = x.saturating_mul(-1).clamp(0, i64::from(top_width)) as u32;
208    let origin_top_y = y.saturating_mul(-1).clamp(0, i64::from(top_height)) as u32;
209
210    (
211        origin_bottom_x,
212        origin_bottom_y,
213        origin_top_x,
214        origin_top_y,
215        x_range,
216        y_range,
217    )
218}
219
220pub fn overlay<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
222where
223    I: GenericImage,
224    J: GenericImageView<Pixel = I::Pixel>,
225{
226    let bottom_dims = bottom.dimensions();
227    let top_dims = top.dimensions();
228
229    let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) =
231        overlay_bounds_ext(bottom_dims, top_dims, x, y);
232
233    for y in 0..range_height {
234        for x in 0..range_width {
235            let p = top.get_pixel(origin_top_x + x, origin_top_y + y);
236            let mut bottom_pixel = bottom.get_pixel(origin_bottom_x + x, origin_bottom_y + y);
237            bottom_pixel.blend(&p);
238
239            bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, bottom_pixel);
240        }
241    }
242}
243
244pub fn tile<I, J>(bottom: &mut I, top: &J)
257where
258    I: GenericImage,
259    J: GenericImageView<Pixel = I::Pixel>,
260{
261    for x in (0..bottom.width()).step_by(top.width() as usize) {
262        for y in (0..bottom.height()).step_by(top.height() as usize) {
263            overlay(bottom, top, i64::from(x), i64::from(y));
264        }
265    }
266}
267
268pub fn vertical_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
283where
284    I: GenericImage<Pixel = P>,
285    P: Pixel<Subpixel = S> + 'static,
286    S: Primitive + Lerp + 'static,
287{
288    for y in 0..img.height() {
289        let pixel = start.map2(stop, |a, b| {
290            let y = <S::Ratio as num_traits::NumCast>::from(y).unwrap();
291            let height = <S::Ratio as num_traits::NumCast>::from(img.height() - 1).unwrap();
292            S::lerp(a, b, y / height)
293        });
294
295        for x in 0..img.width() {
296            img.put_pixel(x, y, pixel);
297        }
298    }
299}
300
301pub fn horizontal_gradient<S, P, I>(img: &mut I, start: &P, stop: &P)
316where
317    I: GenericImage<Pixel = P>,
318    P: Pixel<Subpixel = S> + 'static,
319    S: Primitive + Lerp + 'static,
320{
321    for x in 0..img.width() {
322        let pixel = start.map2(stop, |a, b| {
323            let x = <S::Ratio as num_traits::NumCast>::from(x).unwrap();
324            let width = <S::Ratio as num_traits::NumCast>::from(img.width() - 1).unwrap();
325            S::lerp(a, b, x / width)
326        });
327
328        for y in 0..img.height() {
329            img.put_pixel(x, y, pixel);
330        }
331    }
332}
333
334pub fn replace<I, J>(bottom: &mut I, top: &J, x: i64, y: i64)
336where
337    I: GenericImage,
338    J: GenericImageView<Pixel = I::Pixel>,
339{
340    let bottom_dims = bottom.dimensions();
341    let top_dims = top.dimensions();
342
343    let (origin_bottom_x, origin_bottom_y, origin_top_x, origin_top_y, range_width, range_height) =
345        overlay_bounds_ext(bottom_dims, top_dims, x, y);
346
347    for y in 0..range_height {
348        for x in 0..range_width {
349            let p = top.get_pixel(origin_top_x + x, origin_top_y + y);
350            bottom.put_pixel(origin_bottom_x + x, origin_bottom_y + y, p);
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357
358    use super::*;
359    use crate::color::Rgb;
360    use crate::GrayAlphaImage;
361    use crate::GrayImage;
362    use crate::ImageBuffer;
363    use crate::RgbImage;
364    use crate::RgbaImage;
365
366    #[test]
367    fn test_overlay_bounds_ext() {
368        assert_eq!(
369            overlay_bounds_ext((10, 10), (10, 10), 0, 0),
370            (0, 0, 0, 0, 10, 10)
371        );
372        assert_eq!(
373            overlay_bounds_ext((10, 10), (10, 10), 1, 0),
374            (1, 0, 0, 0, 9, 10)
375        );
376        assert_eq!(
377            overlay_bounds_ext((10, 10), (10, 10), 0, 11),
378            (0, 0, 0, 0, 0, 0)
379        );
380        assert_eq!(
381            overlay_bounds_ext((10, 10), (10, 10), -1, 0),
382            (0, 0, 1, 0, 9, 10)
383        );
384        assert_eq!(
385            overlay_bounds_ext((10, 10), (10, 10), -10, 0),
386            (0, 0, 0, 0, 0, 0)
387        );
388        assert_eq!(
389            overlay_bounds_ext((10, 10), (10, 10), 1i64 << 50, 0),
390            (0, 0, 0, 0, 0, 0)
391        );
392        assert_eq!(
393            overlay_bounds_ext((10, 10), (10, 10), -(1i64 << 50), 0),
394            (0, 0, 0, 0, 0, 0)
395        );
396        assert_eq!(
397            overlay_bounds_ext((10, 10), (u32::MAX, 10), 10 - i64::from(u32::MAX), 0),
398            (0, 0, u32::MAX - 10, 0, 10, 10)
399        );
400    }
401
402    #[test]
403    fn test_image_in_image() {
405        let mut target = ImageBuffer::new(32, 32);
406        let source = ImageBuffer::from_pixel(16, 16, Rgb([255u8, 0, 0]));
407        overlay(&mut target, &source, 0, 0);
408        assert!(*target.get_pixel(0, 0) == Rgb([255u8, 0, 0]));
409        assert!(*target.get_pixel(15, 0) == Rgb([255u8, 0, 0]));
410        assert!(*target.get_pixel(16, 0) == Rgb([0u8, 0, 0]));
411        assert!(*target.get_pixel(0, 15) == Rgb([255u8, 0, 0]));
412        assert!(*target.get_pixel(0, 16) == Rgb([0u8, 0, 0]));
413    }
414
415    #[test]
416    fn test_image_in_image_outside_of_bounds() {
418        let mut target = ImageBuffer::new(32, 32);
419        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
420        overlay(&mut target, &source, 1, 1);
421        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
422        assert!(*target.get_pixel(1, 1) == Rgb([255u8, 0, 0]));
423        assert!(*target.get_pixel(31, 31) == Rgb([255u8, 0, 0]));
424    }
425
426    #[test]
427    fn test_image_outside_image_no_wrap_around() {
430        let mut target = ImageBuffer::new(32, 32);
431        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
432        overlay(&mut target, &source, 33, 33);
433        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
434        assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
435        assert!(*target.get_pixel(31, 31) == Rgb([0, 0, 0]));
436    }
437
438    #[test]
439    fn test_image_coordinate_overflow() {
441        let mut target = ImageBuffer::new(16, 16);
442        let source = ImageBuffer::from_pixel(32, 32, Rgb([255u8, 0, 0]));
443        overlay(
445            &mut target,
446            &source,
447            i64::from(u32::MAX - 31),
448            i64::from(u32::MAX - 31),
449        );
450        assert!(*target.get_pixel(0, 0) == Rgb([0, 0, 0]));
451        assert!(*target.get_pixel(1, 1) == Rgb([0, 0, 0]));
452        assert!(*target.get_pixel(15, 15) == Rgb([0, 0, 0]));
453    }
454
455    use super::{horizontal_gradient, vertical_gradient};
456
457    #[test]
458    fn test_image_horizontal_gradient_limits() {
460        let mut img = ImageBuffer::new(100, 1);
461
462        let start = Rgb([0u8, 128, 0]);
463        let end = Rgb([255u8, 255, 255]);
464
465        horizontal_gradient(&mut img, &start, &end);
466
467        assert_eq!(img.get_pixel(0, 0), &start);
468        assert_eq!(img.get_pixel(img.width() - 1, 0), &end);
469    }
470
471    #[test]
472    fn test_image_vertical_gradient_limits() {
474        let mut img = ImageBuffer::new(1, 100);
475
476        let start = Rgb([0u8, 128, 0]);
477        let end = Rgb([255u8, 255, 255]);
478
479        vertical_gradient(&mut img, &start, &end);
480
481        assert_eq!(img.get_pixel(0, 0), &start);
482        assert_eq!(img.get_pixel(0, img.height() - 1), &end);
483    }
484
485    #[test]
486    fn test_blur_zero() {
488        let image = RgbaImage::new(50, 50);
489        let _ = blur(&image, 0.0);
490    }
491
492    #[test]
493    fn test_fast_blur_zero() {
495        let image = RgbaImage::new(50, 50);
496        let _ = fast_blur(&image, 0.0);
497    }
498
499    #[test]
500    fn test_fast_blur_negative() {
502        let image = RgbaImage::new(50, 50);
503        let _ = fast_blur(&image, -1.0);
504    }
505
506    #[test]
507    fn test_fast_large_sigma() {
509        let image = RgbaImage::new(1, 1);
510        let _ = fast_blur(&image, 50.0);
511    }
512
513    #[test]
514    fn test_fast_blur_empty() {
516        let image = RgbaImage::new(0, 0);
517        let _ = fast_blur(&image, 1.0);
518        let image = RgbaImage::new(20, 0);
519        let _ = fast_blur(&image, 1.0);
520        let image = RgbaImage::new(0, 20);
521        let _ = fast_blur(&image, 1.0);
522    }
523
524    #[test]
525    fn test_fast_blur_3_channels() {
527        let image = RgbImage::new(50, 50);
528        let _ = fast_blur(&image, 1.0);
529    }
530
531    #[test]
532    fn test_fast_blur_2_channels() {
534        let image = GrayAlphaImage::new(50, 50);
535        let _ = fast_blur(&image, 1.0);
536    }
537
538    #[test]
539    fn test_fast_blur_1_channels() {
541        let image = GrayImage::new(50, 50);
542        let _ = fast_blur(&image, 1.0);
543    }
544
545    #[test]
546    #[cfg(feature = "tiff")]
547    fn fast_blur_approximates_gaussian_blur_well() {
548        let path = concat!(
549            env!("CARGO_MANIFEST_DIR"),
550            "/tests/images/tiff/testsuite/rgb-3c-16b.tiff"
551        );
552        let image = crate::open(path).unwrap();
553        let image_blurred_gauss = image.blur(50.0).to_rgb8();
554        let image_blurred_gauss_samples = image_blurred_gauss.as_flat_samples();
555        let image_blurred_gauss_bytes = image_blurred_gauss_samples.as_slice();
556        let image_blurred_fast = image.fast_blur(50.0).to_rgb8();
557        let image_blurred_fast_samples = image_blurred_fast.as_flat_samples();
558        let image_blurred_fast_bytes = image_blurred_fast_samples.as_slice();
559
560        let error = image_blurred_gauss_bytes
561            .iter()
562            .zip(image_blurred_fast_bytes.iter())
563            .map(|(a, b)| ((f32::from(*a) - f32::from(*b)) / f32::from(*a)))
564            .sum::<f32>()
565            / (image_blurred_gauss_bytes.len() as f32);
566        assert!(error < 0.05);
567    }
568}