laravel-image 0.2.0

Image handling and manipulation for Laravel Rust, in pure Rust: a port of intervention/image-laravel and Intervention Image.
Documentation
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! The modifiers of Intervention Image 4, with the arithmetic of its GD driver.

use std::collections::VecDeque;

use fast_image_resize::{FilterType, ResizeAlg, ResizeOptions, Resizer as PixelResizer};
use image::{Rgba, RgbaImage};

use crate::color::Color;
#[cfg(doc)]
use crate::error::ImageError;
use crate::error::{Result, invalid};
use crate::geometry::{Alignment, Dimension, Direction, Resizer, Size};
use crate::image::Image;
use crate::manager::{ImageManager, Source};

/// Resample `src` (or its `crop` rectangle: left, top, width, height) to `width` × `height`,
/// alpha-aware, as `imagecopyresampled()` does.
fn resample(src: &RgbaImage, crop: Option<(f64, f64, f64, f64)>, width: u32, height: u32) -> RgbaImage {
    let full = crop
        .is_none_or(|(l, t, w, h)| l == 0.0 && t == 0.0 && w == f64::from(src.width()) && h == f64::from(src.height()));
    if full && src.width() == width && src.height() == height {
        return src.clone();
    }
    let mut dst = RgbaImage::new(width.max(1), height.max(1));
    let mut options = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear));
    if let Some((left, top, w, h)) = crop {
        options = options.crop(left, top, w, h);
    }
    // Both buffers are RGBA8, so the pixel types always match.
    let _ = PixelResizer::new().resize(src, &mut dst, &options);
    dst
}

/// Draw `src` over `dst` at `x`, `y` with "over" alpha compositing (`imagealphablending` on).
fn blend(dst: &mut RgbaImage, src: &RgbaImage, x: i64, y: i64) {
    for (sx, sy, pixel) in src.enumerate_pixels() {
        let (dx, dy) = (x + i64::from(sx), y + i64::from(sy));
        if dx < 0 || dy < 0 || dx >= i64::from(dst.width()) || dy >= i64::from(dst.height()) {
            continue;
        }
        let target = dst.get_pixel_mut(dx as u32, dy as u32);
        *target = over(*pixel, *target);
    }
}

/// GD keeps alpha in 7 bits (`0` opaque, `127` transparent); blending happens in that range.
fn to_gd_alpha(alpha: u8) -> i32 {
    127 - i32::from(alpha >> 1)
}

fn from_gd_alpha(alpha: i32) -> u8 {
    (f64::from(127 - alpha) * 255.0 / 127.0).round() as u8
}

/// `gdAlphaBlend()`: draw `src` over `dst` with GD's arithmetic.
fn over(src: Rgba<u8>, dst: Rgba<u8>) -> Rgba<u8> {
    let src_alpha = to_gd_alpha(src[3]);
    if src_alpha == 0 {
        return src;
    }
    let dst_alpha = to_gd_alpha(dst[3]);
    if src_alpha == 127 {
        return dst;
    }
    if dst_alpha == 127 {
        return src;
    }
    let src_weight = 127 - src_alpha;
    let dst_weight = (127 - dst_alpha) * src_alpha / 127;
    let total = src_weight + dst_weight;
    let alpha = src_alpha * dst_alpha / 127;
    let channel = |i: usize| ((i32::from(src[i]) * src_weight + i32::from(dst[i]) * dst_weight) / total) as u8;
    Rgba([channel(0), channel(1), channel(2), from_gd_alpha(alpha)])
}

/// Copy `src` onto `dst` at `x`, `y` without blending (`imagealphablending` off).
fn copy(dst: &mut RgbaImage, src: &RgbaImage, x: i64, y: i64) {
    for (sx, sy, pixel) in src.enumerate_pixels() {
        let (dx, dy) = (x + i64::from(sx), y + i64::from(sy));
        if dx >= 0 && dy >= 0 && dx < i64::from(dst.width()) && dy < i64::from(dst.height()) {
            dst.put_pixel(dx as u32, dy as u32, *pixel);
        }
    }
}

fn clamp_u8(value: f64) -> u8 {
    value.clamp(0.0, 255.0) as u8
}

fn map_pixels(buffer: &mut RgbaImage, f: impl Fn([u8; 4]) -> [u8; 4]) {
    for pixel in buffer.pixels_mut() {
        pixel.0 = f(pixel.0);
    }
}

/// A 3×3 convolution with clamped edges and the center pixel's alpha (`imageconvolution`).
fn convolve(buffer: &RgbaImage, matrix: [[f64; 3]; 3], divisor: f64) -> RgbaImage {
    let (width, height) = buffer.dimensions();
    let mut out = RgbaImage::new(width, height);
    for y in 0..height {
        for x in 0..width {
            let mut sum = [0.0f64; 3];
            for (j, row) in matrix.iter().enumerate() {
                let sy = (i64::from(y) - 1 + j as i64).clamp(0, i64::from(height) - 1) as u32;
                for (i, weight) in row.iter().enumerate() {
                    let sx = (i64::from(x) - 1 + i as i64).clamp(0, i64::from(width) - 1) as u32;
                    let pixel = buffer.get_pixel(sx, sy);
                    for (c, total) in sum.iter_mut().enumerate() {
                        *total += f64::from(pixel[c]) * weight;
                    }
                }
            }
            let alpha = buffer.get_pixel(x, y)[3];
            out.put_pixel(
                x,
                y,
                Rgba([
                    clamp_u8((sum[0] / divisor).round()),
                    clamp_u8((sum[1] / divisor).round()),
                    clamp_u8((sum[2] / divisor).round()),
                    alpha,
                ]),
            );
        }
    }
    out
}

fn rotate_exact(buffer: &RgbaImage, quarter_turns: u32) -> RgbaImage {
    match quarter_turns % 4 {
        1 => image::imageops::rotate90(buffer),
        2 => image::imageops::rotate180(buffer),
        3 => image::imageops::rotate270(buffer),
        _ => buffer.clone(),
    }
}

/// Rotate clockwise by `degrees`, filling the new corners with `background`, bilinear.
fn rotate_free(buffer: &RgbaImage, degrees: f64, background: Rgba<u8>) -> RgbaImage {
    let (w, h) = (f64::from(buffer.width()), f64::from(buffer.height()));
    let radians = degrees.to_radians();
    let (sin, cos) = radians.sin_cos();
    let new_w = (w * cos.abs() + h * sin.abs()).round().max(1.0) as u32;
    let new_h = (w * sin.abs() + h * cos.abs()).round().max(1.0) as u32;
    let (cx, cy) = (w / 2.0, h / 2.0);
    let (ncx, ncy) = (f64::from(new_w) / 2.0, f64::from(new_h) / 2.0);
    let sample = |x: i64, y: i64| -> [f64; 4] {
        if x < 0 || y < 0 || x >= i64::from(buffer.width()) || y >= i64::from(buffer.height()) {
            background.0.map(f64::from)
        } else {
            buffer.get_pixel(x as u32, y as u32).0.map(f64::from)
        }
    };
    let mut out = RgbaImage::new(new_w, new_h);
    for (x, y, pixel) in out.enumerate_pixels_mut() {
        let dx = f64::from(x) + 0.5 - ncx;
        let dy = f64::from(y) + 0.5 - ncy;
        // Inverse of a clockwise rotation (y axis points down).
        let sx = dx * cos + dy * sin + cx - 0.5;
        let sy = -dx * sin + dy * cos + cy - 0.5;
        if sx < -1.0 || sy < -1.0 || sx > w || sy > h {
            *pixel = background;
            continue;
        }
        let (x0, y0) = (sx.floor(), sy.floor());
        let (fx, fy) = (sx - x0, sy - y0);
        let (x0, y0) = (x0 as i64, y0 as i64);
        let corners = [
            sample(x0, y0),
            sample(x0 + 1, y0),
            sample(x0, y0 + 1),
            sample(x0 + 1, y0 + 1),
        ];
        let mut value = [0u8; 4];
        for (c, channel) in value.iter_mut().enumerate() {
            let top = corners[0][c] * (1.0 - fx) + corners[1][c] * fx;
            let bottom = corners[2][c] * (1.0 - fx) + corners[3][c] * fx;
            *channel = clamp_u8((top * (1.0 - fy) + bottom * fy).round());
        }
        *pixel = Rgba(value);
    }
    out
}

impl Image {
    fn dimensions(&self, width: Dimension, height: Dimension) -> (Option<i64>, Option<i64>) {
        (width.resolve(self.width()), height.resolve(self.height()))
    }

    fn resize_to(&mut self, size: Size) {
        let (width, height) = (size.width(), size.height());
        self.map_frames(|buffer| resample(buffer, None, width, height));
    }

    fn background_or(&self, background: Option<&str>) -> Result<Color> {
        match background {
            Some(color) => Color::parse(color),
            None => self.config.background(),
        }
    }

    /// `resize($width, $height)`: resize to exactly the given size; `None` keeps that side.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] when both sides are `None` or a side is smaller than 1.
    pub fn resize(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
        let (width, height) = self.dimensions(width.into(), height.into());
        if width.is_none() && height.is_none() {
            return Err(invalid(
                "At least one argument must be provided: width, height, or both.",
            ));
        }
        let size = Resizer::new(width, height)?.resize(&self.size());
        self.resize_to(size);
        Ok(self)
    }

    /// `resizeDown($width, $height)`: like [`resize`](Self::resize), never upsizing.
    ///
    /// # Errors
    ///
    /// As [`resize`](Self::resize).
    pub fn resize_down(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
        let (width, height) = self.dimensions(width.into(), height.into());
        if width.is_none() && height.is_none() {
            return Err(invalid(
                "At least one argument must be provided: width, height, or both.",
            ));
        }
        let size = Resizer::new(width, height)?.resize_down(&self.size());
        self.resize_to(size);
        Ok(self)
    }

    /// `scale($width, $height)`: resize keeping the aspect ratio, within the given size.
    ///
    /// # Errors
    ///
    /// As [`resize`](Self::resize).
    pub fn scale(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
        let (width, height) = self.dimensions(width.into(), height.into());
        if width.is_none() && height.is_none() {
            return Err(invalid(
                "At least one argument must be provided: width, height, or both.",
            ));
        }
        let size = Resizer::new(width, height)?.scale(&self.size());
        self.resize_to(size);
        Ok(self)
    }

    /// `scaleDown($width, $height)`: like [`scale`](Self::scale), never upsizing.
    ///
    /// # Errors
    ///
    /// As [`resize`](Self::resize).
    pub fn scale_down(&mut self, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Result<&mut Self> {
        let (width, height) = self.dimensions(width.into(), height.into());
        if width.is_none() && height.is_none() {
            return Err(invalid(
                "At least one argument must be provided: width, height, or both.",
            ));
        }
        let size = Resizer::new(width, height)?.scale_down(&self.size());
        self.resize_to(size);
        Ok(self)
    }

    fn cover_with(&mut self, width: Dimension, height: Dimension, alignment: Alignment, down: bool) -> Result<()> {
        let (Some(width), Some(height)) = self.dimensions(width, height) else {
            return Err(invalid("Width and height are required"));
        };
        let image_size = self.size();
        let mut crop = Resizer::new(Some(image_size.width().into()), Some(image_size.height().into()))?
            .contain(&Size::new(width, height)?)?;
        crop.align_pivot_to(&image_size, alignment);
        let resizer = Resizer::new(Some(width), Some(height))?;
        let resize = if down {
            resizer.resize_down(&crop)
        } else {
            resizer.resize(&crop)
        };
        let rect = (
            crop.pivot().x as f64,
            crop.pivot().y as f64,
            f64::from(crop.width()),
            f64::from(crop.height()),
        );
        let (w, h) = (resize.width(), resize.height());
        self.map_frames(|buffer| resample(buffer, Some(rect), w, h));
        Ok(())
    }

    /// `cover($width, $height, $alignment)`: crop to the aspect ratio of the given size at the
    /// alignment, then resize to exactly that size.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a side smaller than 1.
    pub fn cover(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.cover_with(width.into(), height.into(), alignment, false)?;
        Ok(self)
    }

    /// `coverDown($width, $height, $alignment)`: like [`cover`](Self::cover), never upsizing.
    ///
    /// # Errors
    ///
    /// As [`cover`](Self::cover).
    pub fn cover_down(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.cover_with(width.into(), height.into(), alignment, true)?;
        Ok(self)
    }

    fn contain_with(
        &mut self,
        width: Dimension,
        height: Dimension,
        background: Option<&str>,
        alignment: Alignment,
        down: bool,
    ) -> Result<()> {
        let (Some(width), Some(height)) = self.dimensions(width, height) else {
            return Err(invalid("Width and height are required"));
        };
        let canvas = Size::new(width, height)?;
        let resizer = Resizer::new(Some(width), Some(height))?;
        let mut crop = if down {
            resizer.contain_down(&self.size())?
        } else {
            resizer.contain(&self.size())?
        };
        crop.align_pivot_to(&canvas, alignment);
        let background = self.background_or(background)?.to_pixel();
        let (cw, ch) = (crop.width(), crop.height());
        let pivot = crop.pivot();
        self.map_frames(|buffer| {
            let mut out = RgbaImage::from_pixel(canvas.width(), canvas.height(), background);
            copy(&mut out, &resample(buffer, None, cw, ch), pivot.x, pivot.y);
            out
        });
        Ok(())
    }

    /// `contain($width, $height, $background, $alignment)`: resize to fit within the given size
    /// and fill the rest of the canvas with `background` (the configured background color when
    /// `None`).
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a side smaller than 1,
    /// [`ImageError::ColorDecoder`] for a bad color.
    pub fn contain(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        background: Option<&str>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.contain_with(width.into(), height.into(), background, alignment, false)?;
        Ok(self)
    }

    /// `containDown($width, $height, $background, $alignment)`: like
    /// [`contain`](Self::contain), never upsizing the image itself.
    ///
    /// # Errors
    ///
    /// As [`contain`](Self::contain).
    pub fn contain_down(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        background: Option<&str>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.contain_with(width.into(), height.into(), background, alignment, true)?;
        Ok(self)
    }

    /// `crop($width, $height, $x, $y, $background, $alignment)`: cut out a rectangle positioned by
    /// the alignment and the offset; areas outside the image get `background`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a negative side, [`ImageError::ColorDecoder`] for a
    /// bad color.
    pub fn crop(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        x: i64,
        y: i64,
        background: Option<&str>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        let (Some(width), Some(height)) = self.dimensions(width.into(), height.into()) else {
            return Err(invalid("Width and height are required"));
        };
        let mut crop = Size::new(width, height)?;
        crop.move_pivot(alignment, 0, 0);
        crop.align_pivot_to(&self.size(), alignment);
        let background = self.background_or(background)?.to_pixel();
        self.crop_frames(
            crop.width(),
            crop.height(),
            crop.pivot().x + x,
            crop.pivot().y + y,
            background,
        );
        Ok(self)
    }

    fn crop_frames(&mut self, width: u32, height: u32, offset_x: i64, offset_y: i64, background: Rgba<u8>) {
        self.map_frames(|buffer| {
            let mut out = RgbaImage::from_pixel(width.max(1), height.max(1), background);
            copy(&mut out, buffer, -offset_x, -offset_y);
            out
        });
    }

    fn resize_canvas_with(
        &mut self,
        width: Dimension,
        height: Dimension,
        background: Option<&str>,
        alignment: Alignment,
        relative: bool,
    ) -> Result<()> {
        let (width, height) = self.dimensions(width, height);
        let (current_w, current_h) = (i64::from(self.width()), i64::from(self.height()));
        let (w, h) = if relative {
            (
                width.map_or(current_w, |w| current_w + w),
                height.map_or(current_h, |h| current_h + h),
            )
        } else {
            (width.unwrap_or(current_w), height.unwrap_or(current_h))
        };
        let mut size = Size::new(w, h)?;
        size.align_pivot_to(&self.size(), alignment);
        let background = self.background_or(background)?.to_pixel();
        self.crop_frames(size.width(), size.height(), size.pivot().x, size.pivot().y, background);
        Ok(())
    }

    /// `resizeCanvas($width, $height, $background, $alignment)`: change the canvas size, keeping
    /// the image at the alignment; new areas get `background`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a negative side, [`ImageError::ColorDecoder`] for a
    /// bad color.
    pub fn resize_canvas(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        background: Option<&str>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.resize_canvas_with(width.into(), height.into(), background, alignment, false)?;
        Ok(self)
    }

    /// `resizeCanvasRelative($width, $height, $background, $alignment)`: grow (or shrink) the
    /// canvas by the given amounts.
    ///
    /// # Errors
    ///
    /// As [`resize_canvas`](Self::resize_canvas).
    pub fn resize_canvas_relative(
        &mut self,
        width: impl Into<Dimension>,
        height: impl Into<Dimension>,
        background: Option<&str>,
        alignment: Alignment,
    ) -> Result<&mut Self> {
        self.resize_canvas_with(width.into(), height.into(), background, alignment, true)?;
        Ok(self)
    }

    /// `rotate($angle, $background)`: rotate clockwise by `angle` degrees; uncovered areas get
    /// `background` (the configured background color when `None`).
    ///
    /// # Errors
    ///
    /// [`ImageError::ColorDecoder`] for a bad color.
    pub fn rotate(&mut self, angle: f64, background: Option<&str>) -> Result<&mut Self> {
        let background = self.background_or(background)?.to_pixel();
        let angle = angle % 360.0;
        let normalized = if angle < 0.0 { angle + 360.0 } else { angle };
        if normalized % 90.0 == 0.0 {
            let turns = (normalized / 90.0) as u32;
            self.map_frames(|buffer| rotate_exact(buffer, turns));
        } else {
            self.map_frames(|buffer| rotate_free(buffer, normalized, background));
        }
        Ok(self)
    }

    /// `orient()`: rotate and flip according to the Exif orientation, then mark it as aligned
    /// (`Orientation` = 1). Applied on decoding when `autoOrientation` is on.
    pub fn orient(&mut self) -> &mut Self {
        let orientation = self.exif.orientation().unwrap_or(0);
        match orientation {
            2 => self.flip(Direction::Horizontal),
            3 => self.rotate_quarters(2),
            4 => self.rotate_quarters(2).flip(Direction::Horizontal),
            5 => self.rotate_quarters(1).flip(Direction::Horizontal),
            6 => self.rotate_quarters(1),
            7 => self.rotate_quarters(3).flip(Direction::Horizontal),
            8 => self.rotate_quarters(3),
            _ => self,
        };
        self.exif.set_orientation(1);
        self
    }

    fn rotate_quarters(&mut self, turns: u32) -> &mut Self {
        self.map_frames(|buffer| rotate_exact(buffer, turns));
        self
    }

    /// `flip($direction)`: mirror horizontally (the default in PHP) or vertically.
    pub fn flip(&mut self, direction: Direction) -> &mut Self {
        self.each_frame(|buffer| match direction {
            Direction::Horizontal => image::imageops::flip_horizontal_in_place(buffer),
            Direction::Vertical => image::imageops::flip_vertical_in_place(buffer),
        });
        self
    }

    /// `grayscale()`.
    pub fn grayscale(&mut self) -> &mut Self {
        self.each_frame(|buffer| {
            map_pixels(buffer, |[r, g, b, a]| {
                let gray = (0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b)) as u8;
                [gray, gray, gray, a]
            });
        });
        self
    }

    /// `invert()`: negate the colors.
    pub fn invert(&mut self) -> &mut Self {
        self.each_frame(|buffer| map_pixels(buffer, |[r, g, b, a]| [255 - r, 255 - g, 255 - b, a]));
        self
    }

    /// `brightness($level)`: `-100` to `100`.
    pub fn brightness(&mut self, level: i32) -> &mut Self {
        let amount = ((f64::from(level) * 2.55) as i64).clamp(-255, 255) as f64;
        self.each_frame(|buffer| {
            map_pixels(buffer, |[r, g, b, a]| {
                let adjust = |c: u8| clamp_u8(f64::from(c) + amount);
                [adjust(r), adjust(g), adjust(b), a]
            });
        });
        self
    }

    /// `contrast($level)`: `-100` to `100`.
    pub fn contrast(&mut self, level: i32) -> &mut Self {
        let factor = ((100.0 + f64::from(level)) / 100.0).powi(2);
        self.each_frame(|buffer| {
            map_pixels(buffer, |[r, g, b, a]| {
                let adjust = |c: u8| clamp_u8(((f64::from(c) / 255.0 - 0.5) * factor + 0.5) * 255.0);
                [adjust(r), adjust(g), adjust(b), a]
            });
        });
        self
    }

    /// `gamma($gamma)`.
    pub fn gamma(&mut self, gamma: f64) -> &mut Self {
        let exponent = 1.0 / gamma;
        self.each_frame(|buffer| {
            map_pixels(buffer, |[r, g, b, a]| {
                let adjust = |c: u8| clamp_u8((f64::from(c) / 255.0).powf(exponent) * 255.0 + 0.5);
                [adjust(r), adjust(g), adjust(b), a]
            });
        });
        self
    }

    /// `colorize($red, $green, $blue)`: shift each channel by `-100` to `100`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a level outside `-100..=100`.
    pub fn colorize(&mut self, red: i32, green: i32, blue: i32) -> Result<&mut Self> {
        for (name, level) in [("red", red), ("green", green), ("blue", blue)] {
            if !(-100..=100).contains(&level) {
                return Err(invalid(format!(
                    "Color level for argument ${name} must be in range -100 to 100"
                )));
            }
        }
        let scale = |level: i32| (f64::from(level) * 2.55).round();
        let (dr, dg, db) = (scale(red), scale(green), scale(blue));
        self.each_frame(|buffer| {
            map_pixels(buffer, |[r, g, b, a]| {
                [
                    clamp_u8(f64::from(r) + dr),
                    clamp_u8(f64::from(g) + dg),
                    clamp_u8(f64::from(b) + db),
                    a,
                ]
            });
        });
        Ok(self)
    }

    /// `blur($level)`: apply a 3×3 Gaussian blur `level` times (5 in PHP by default).
    pub fn blur(&mut self, level: u32) -> &mut Self {
        let kernel = [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]];
        self.each_frame(|buffer| {
            for _ in 0..level {
                *buffer = convolve(buffer, kernel, 16.0);
            }
        });
        self
    }

    /// `sharpen($level)`: 10 in PHP by default.
    pub fn sharpen(&mut self, level: u32) -> &mut Self {
        let level = f64::from(level);
        let min = if level >= 10.0 { level * -0.01 } else { 0.0 };
        let max = level * -0.025;
        let abs = -(4.0 * min + 4.0 * max) + 1.0;
        let matrix = [[min, max, min], [max, abs, max], [min, max, min]];
        self.each_frame(|buffer| *buffer = convolve(buffer, matrix, 1.0));
        self
    }

    /// `pixelate($size)`: average blocks of `size` × `size` pixels.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] when `size` is 0.
    pub fn pixelate(&mut self, size: u32) -> Result<&mut Self> {
        if size < 1 {
            return Err(invalid("Invalid pixelation size. Must be int<1, max>"));
        }
        self.each_frame(|buffer| {
            let (width, height) = buffer.dimensions();
            for by in (0..height).step_by(size as usize) {
                for bx in (0..width).step_by(size as usize) {
                    let (ex, ey) = ((bx + size).min(width), (by + size).min(height));
                    let mut sum = [0u64; 4];
                    for y in by..ey {
                        for x in bx..ex {
                            for (total, value) in sum.iter_mut().zip(buffer.get_pixel(x, y).0) {
                                *total += u64::from(value);
                            }
                        }
                    }
                    let count = u64::from((ex - bx) * (ey - by));
                    let average = Rgba(sum.map(|total| (total / count) as u8));
                    for y in by..ey {
                        for x in bx..ex {
                            buffer.put_pixel(x, y, average);
                        }
                    }
                }
            }
        });
        Ok(self)
    }

    /// `insert($image, $x, $y, $alignment, $transparency)`: draw another image (a path, bytes,
    /// an [`Image`], ...) on every frame at the alignment and offset. `transparency` is the
    /// opacity of the inserted image, `0.0` to `1.0`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for a transparency outside `0..=1`, the decoding errors
    /// of the inserted image.
    pub fn insert(
        &mut self,
        source: impl Into<Source>,
        x: i64,
        y: i64,
        alignment: Alignment,
        transparency: f64,
    ) -> Result<&mut Self> {
        if !(0.0..=1.0).contains(&transparency) {
            return Err(invalid("Transparency must be in range 0 to 1"));
        }
        let watermark = ImageManager::new(self.config.clone()).decode(source)?;
        let mut mark = watermark.first().clone();
        if transparency < 1.0 {
            // GD's `fadeWatermark()`, in its 7-bit alpha.
            map_pixels(&mut mark, |[r, g, b, a]| {
                let alpha = 127 - (f64::from(127 - to_gd_alpha(a)) * transparency).round() as i32;
                [r, g, b, from_gd_alpha(alpha)]
            });
        }
        let mut image_size = self.size();
        image_size.move_pivot(alignment, x, y);
        let mut mark_size = watermark.size();
        mark_size.move_pivot(alignment, 0, 0);
        let position = image_size.offset_to(&mark_size);
        self.each_frame(|buffer| blend(buffer, &mark, position.x, position.y));
        Ok(self)
    }

    /// `fill($color, $x, $y)`: fill the whole image with `color` (blended over it), or, with a
    /// position, flood-fill the area of the color at that position.
    ///
    /// # Errors
    ///
    /// [`ImageError::ColorDecoder`] for a bad color.
    pub fn fill(&mut self, color: &str, x: Option<u32>, y: Option<u32>) -> Result<&mut Self> {
        let color = Color::parse(color)?.to_pixel();
        match (x, y) {
            (Some(x), Some(y)) => self.each_frame(|buffer| flood_fill(buffer, x, y, color)),
            _ => self.each_frame(|buffer| {
                for pixel in buffer.pixels_mut() {
                    *pixel = over(color, *pixel);
                }
            }),
        }
        Ok(self)
    }
}

fn flood_fill(buffer: &mut RgbaImage, x: u32, y: u32, color: Rgba<u8>) {
    if x >= buffer.width() || y >= buffer.height() {
        return;
    }
    let target = *buffer.get_pixel(x, y);
    if target == color {
        return;
    }
    let mut queue = VecDeque::from([(x, y)]);
    while let Some((x, y)) = queue.pop_front() {
        if *buffer.get_pixel(x, y) != target {
            continue;
        }
        buffer.put_pixel(x, y, color);
        if x > 0 {
            queue.push_back((x - 1, y));
        }
        if y > 0 {
            queue.push_back((x, y - 1));
        }
        if x + 1 < buffer.width() {
            queue.push_back((x + 1, y));
        }
        if y + 1 < buffer.height() {
            queue.push_back((x, y + 1));
        }
    }
}