ril 0.10.3

Rust Imaging Library: A performant and high-level image processing crate for Rust
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
#![allow(clippy::wildcard_imports)]

use crate::{
    draw::Draw,
    error::{Error, Result},
    format::ImageFormat,
    pixel::*,
    Dynamic,
};

#[cfg(feature = "resize")]
use crate::ResizeAlgorithm;

use num_traits::{SaturatingAdd, SaturatingSub};
use std::{
    fmt::{self, Display},
    fs::File,
    io::{Read, Write},
    num::NonZeroU32,
    path::Path,
};

/// The behavior to use when overlaying images on top of each other.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum OverlayMode {
    /// Replace alpha values with the alpha values of the overlay image. This is the default
    /// behavior.
    Replace,
    /// Merge the alpha values of overlay image with the alpha values of the base image.
    Merge,
}

impl Default for OverlayMode {
    fn default() -> Self {
        Self::Replace
    }
}

impl Display for OverlayMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Merge => write!(f, "merge"),
            Self::Replace => write!(f, "replace"),
        }
    }
}

/// A high-level image representation.
///
/// This represents a static, single-frame image.
/// See [`crate::ImageSequence`] for information on opening animated or multi-frame images.
#[derive(Clone)]
pub struct Image<P: Pixel> {
    pub(crate) width: NonZeroU32,
    pub(crate) height: NonZeroU32,
    /// A 1-dimensional vector of pixels representing all pixels in the image. This is shaped
    /// according to the image's width and height to form the image.
    ///
    /// This data is a low-level, raw representation of the image. You can see the various pixel
    /// mapping functions, or use the [`pixels`][Image::pixels] method directly for higher level
    /// representations of the data.
    pub data: Vec<P>,
    pub(crate) format: ImageFormat,
    pub(crate) overlay: OverlayMode,
    pub(crate) palette: Option<Box<[P::Color]>>,
}

macro_rules! assert_nonzero {
    ($width:expr) => {{
        debug_assert_ne!($width, 0, "width must be non-zero");
    }};
    ($width:expr, $height:expr) => {{
        assert_nonzero!($width);
        debug_assert_ne!($height, 0, "height must be non-zero");
    }};
}

impl<P: Pixel> Image<P> {
    /// Creates a new image with the given width and height, with all pixels being set
    /// intially to `fill`.
    ///
    /// Both the width and height must be non-zero, or else this will panic. You should validate
    /// the width and height before calling this function.
    ///
    /// # Panics
    /// * `width` or `height` is zero.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// // 16x16 RGB image with all pixels set to white
    /// let image = Image::new(16, 16, Rgb::white());
    ///
    /// assert_eq!(image.width(), 16);
    /// assert_eq!(image.height(), 16);
    /// assert_eq!(image.pixel(0, 0), &Rgb::white());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn new(width: u32, height: u32, fill: P) -> Self {
        assert_nonzero!(width, height);

        Self {
            width: NonZeroU32::new(width).unwrap(),
            height: NonZeroU32::new(height).unwrap(),
            data: vec![fill; (width * height) as usize],
            format: ImageFormat::default(),
            overlay: OverlayMode::default(),
            palette: None,
        }
    }

    /// Creates a new image with the given width and height. The pixels are then resolved through
    /// then given callback function which takes two parameters (the x and y coordinates of each
    /// pixel) and returns a pixel.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let gradient = Image::from_fn(256, 256, |x, _y| L(x as u8));
    ///
    /// assert_eq!(gradient.pixel(0, 0), &L(0));
    /// assert_eq!(gradient.pixel(255, 0), &L(255));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn from_fn(width: u32, height: u32, f: impl Fn(u32, u32) -> P) -> Self {
        Self::new(width, height, P::default()).map_pixels_with_coords(|x, y, _| f(x, y))
    }

    /// Creates a new image shaped with the given width and a 1-dimensional sequence of pixels
    /// which will be shaped according to the width.
    ///
    /// # Panics
    /// * The length of the pixels is not a multiple of the width.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::from_pixels(2, &[L(0), L(1), L(2), L(3)]);
    ///
    /// assert_eq!(image.width(), 2);
    /// assert_eq!(image.height(), 2);
    /// assert_eq!(image.pixel(1, 1), &L(3));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn from_pixels(width: u32, pixels: impl AsRef<[P]>) -> Self {
        assert_nonzero!(width);
        let pixels = pixels.as_ref();

        assert_eq!(
            pixels.len() % width as usize,
            0,
            "length of pixels must be a multiple of the image width",
        );

        Self {
            width: NonZeroU32::new(width).unwrap(),
            // SAFETY: We have already asserted the width being non-zero above with addition to
            // the height being a multiple of the width, meaning that the height cannot be zero.
            height: unsafe { NonZeroU32::new_unchecked(pixels.len() as u32 / width) },
            data: pixels.to_vec(),
            format: ImageFormat::default(),
            overlay: OverlayMode::default(),
            palette: None,
        }
    }

    /// Creates a new image shaped with the given width and a 1-dimensional sequence of paletted
    /// pixels which will be shaped according to the width.
    ///
    /// # Panics
    /// * The length of the pixels is not a multiple of the width.
    /// * The palette is empty.
    /// * The a pixel index is out of bounds with regards to the palette.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::<PalettedRgb>::from_paletted_pixels(
    ///     2,
    ///     vec![Rgb::white(), Rgb::black()],
    ///     &[0, 1, 0, 1],
    /// );
    /// assert_eq!(image.pixel(1, 1).color(), Rgb::black());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn from_paletted_pixels<'p>(
        width: u32,
        palette: impl ToOwned<Owned = Vec<P::Color>> + 'p,
        pixels: impl AsRef<[P::Subpixel]>,
    ) -> Self
    where
        P: Paletted<'p>,
    {
        assert_nonzero!(width);

        let pixels = pixels.as_ref();
        debug_assert_eq!(
            pixels.len() % width as usize,
            0,
            "length of pixels must be a multiple of the image width",
        );
        #[allow(clippy::redundant_clone)]
        let palette = palette.to_owned().into_boxed_slice();
        debug_assert!(!palette.is_empty(), "palette must not be empty");

        let mut slf = Self {
            width: NonZeroU32::new(width).unwrap(),
            // SAFETY: We have already asserted the width being non-zero above with addition to
            // the height being a multiple of the width, meaning that the height cannot be zero.
            height: unsafe { NonZeroU32::new_unchecked(pixels.len() as u32 / width) },
            data: Vec::new(),
            format: ImageFormat::default(),
            overlay: OverlayMode::default(),
            palette: Some(palette),
        };

        let palette = unsafe {
            slf.palette
                .as_deref()
                // SAFETY: references will be dropped when `Self` is dropped; we can guarantee that
                // 'p is only valid for the lifetime of `Self`.
                .map(|slice| std::slice::from_raw_parts(slice.as_ptr(), slice.len()))
                // SAFETY: declared palette as `Some` in struct declaration
                .unwrap_unchecked()
        };

        slf.data = pixels
            .iter()
            .map(|&p| P::from_palette(palette, p))
            .collect();
        slf
    }

    /// Decodes an image with the explicitly given image encoding from the raw byte stream.
    ///
    /// # Errors
    /// * `DecodingError`: The image could not be decoded, maybe it is corrupt.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let file = std::fs::File::open("image.png")?;
    /// let image = Image::<Rgb>::from_reader(ImageFormat::Png, file)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_reader(format: ImageFormat, bytes: impl Read) -> Result<Self> {
        format.run_decoder(bytes)
    }

    /// Decodes an image from the given read stream of bytes, inferring its encoding.
    ///
    /// # Errors
    /// * `DecodingError`: The image could not be decoded, maybe it is corrupt.
    /// * `UnknownEncodingFormat`: Could not infer the encoding from the image. Try explicitly
    ///   specifying it.
    ///
    /// # Panics
    /// * No decoder implementation for the given encoding format.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let file = std::fs::File::open("image.png")?;
    /// let image = Image::<Rgb>::from_reader_inferred(file)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_reader_inferred(mut bytes: impl Read) -> Result<Self> {
        let buf = &mut [0; 12];
        let n = bytes.read(buf)?;

        match ImageFormat::infer_encoding(buf) {
            ImageFormat::Unknown => Err(Error::UnknownEncodingFormat),
            format => format.run_decoder((&buf[..n]).chain(bytes)),
        }
    }

    /// Decodes an image with the explicitly given image encoding from the given bytes.
    /// Could be useful in conjunction with the `include_bytes!` macro.
    ///
    /// Currently, this is not any different from [`from_reader`].
    ///
    /// # Errors
    /// * `DecodingError`: The image could not be decoded, maybe it is corrupt.
    ///
    /// # Panics
    /// * No decoder implementation for the given encoding format.
    ///
    /// # Examples
    /// ```no_run,ignore
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let bytes = include_bytes!("sample.png") as &[u8];
    /// let image = Image::<Rgb>::from_bytes(ImageFormat::Png, bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_bytes(format: ImageFormat, bytes: impl AsRef<[u8]>) -> Result<Self> {
        format.run_decoder(bytes.as_ref())
    }

    /// Decodes an image from the given bytes, inferring its encoding.
    /// Could be useful in conjunction with the `include_bytes!` macro.
    ///
    /// This is more efficient than [`from_reader_inferred`].
    ///
    /// # Errors
    /// * `DecodingError`: The image could not be decoded, maybe it is corrupt.
    /// * `UnknownEncodingFormat`: Could not infer the encoding from the image. Try explicitly
    ///   specifying it.
    ///
    /// # Panics
    /// * No decoder implementation for the given encoding format.
    ///
    /// # Examples
    /// ```no_run,ignore
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let bytes = include_bytes!("sample.png") as &[u8];
    /// let image = Image::<Rgb>::from_bytes_inferred(bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_bytes_inferred(bytes: impl AsRef<[u8]>) -> Result<Self> {
        match ImageFormat::infer_encoding(bytes.as_ref()) {
            ImageFormat::Unknown => Err(Error::UnknownEncodingFormat),
            format => format.run_decoder(bytes.as_ref()),
        }
    }

    /// Opens a file from the given path and decodes it into an image.
    ///
    /// The encoding of the image is automatically inferred. You can explicitly pass in an encoding
    /// by using the [`from_reader`] method.
    ///
    /// # Errors
    /// * `DecodingError`: The image could not be decoded, maybe it is corrupt.
    /// * `UnknownEncodingFormat`: Could not infer the encoding from the image. Try explicitly
    ///   specifying it.
    /// * `IoError`: The file could not be opened.
    ///
    /// # Panics
    /// * No decoder implementation for the given encoding format.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::<Rgb>::open("sample.png")?;
    /// println!("Image dimensions: {}x{}", image.width(), image.height());
    /// # Ok(())
    /// # }
    /// ```
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let buffer = &mut Vec::new();
        let mut file = File::open(path.as_ref())?;
        file.read_to_end(buffer)?;

        let format = match ImageFormat::from_path(path)? {
            ImageFormat::Unknown => match ImageFormat::infer_encoding(&buffer[0..12]) {
                ImageFormat::Unknown => return Err(Error::UnknownEncodingFormat),
                format => format,
            },
            format => format,
        };

        format.run_decoder(buffer.as_slice())
    }

    /// Encodes the image with the given encoding and writes it to the given write buffer.
    ///
    /// # Errors
    /// * An error occured during encoding.
    ///
    /// # Panics
    /// * No encoder implementation for the given encoding format.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::new(100, 100, Rgb::new(255, 0, 0));
    /// let mut out = Vec::new();
    /// image.encode(ImageFormat::Png, &mut out)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn encode(&self, encoding: ImageFormat, dest: &mut impl Write) -> Result<()> {
        encoding.run_encoder(self, dest)
    }

    /// Saves the image with the given encoding to the given path.
    /// You can try saving to a memory buffer by using the [`Self::encode`] method.
    ///
    /// # Errors
    /// * An error occured during encoding.
    ///
    /// # Panics
    /// * No encoder implementation for the given encoding format.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::new(100, 100, Rgb::new(255, 0, 0));
    /// image.save(ImageFormat::Png, "out.png")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn save(&self, encoding: ImageFormat, path: impl AsRef<Path>) -> Result<()> {
        let mut file = File::create(path).map_err(Error::IoError)?;
        self.encode(encoding, &mut file)
    }

    /// Saves the image to the given path, inferring the encoding from the path/filename extension.
    ///
    /// This is obviously slower than [`Self::save`] since this method itself uses it. You should
    /// only use this method if the filename is dynamic, or if you do not know the desired encoding
    /// before runtime.
    ///
    /// # See Also
    /// * [`Self::save`] for more information on how saving works.
    ///
    /// # Errors
    /// * Could not infer encoding format.
    /// * An error occured during encoding.
    ///
    /// # Panics
    /// * No encoder implementation for the given encoding format.
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::new(100, 100, Rgb::new(255, 0, 0));
    /// image.save_inferred("out.png")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn save_inferred(&self, path: impl AsRef<Path>) -> Result<()> {
        let encoding = ImageFormat::from_path(path.as_ref())?;

        match encoding {
            ImageFormat::Unknown => Err(Error::UnknownEncodingFormat),
            _ => self.save(encoding, path),
        }
    }

    #[inline]
    #[must_use]
    const fn resolve_coordinate(&self, x: u32, y: u32) -> usize {
        if x >= self.width() || y >= self.height() {
            usize::MAX
        } else {
            (y * self.width() + x) as usize
        }
    }

    /// Returns the width of the image.
    #[inline]
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width.get()
    }

    /// Returns the height of the image.
    #[inline]
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height.get()
    }

    /// Returns the nearest pixel coordinates to the center of the image.
    ///
    /// This uses integer division which means if an image dimension is not even, then the value is
    /// rounded down - e.g. a 5x5 image returns ``(2, 2)``, rounded down from ``(2.5, 2.5)``.
    #[inline]
    #[must_use]
    pub const fn center(&self) -> (u32, u32) {
        (self.width() / 2, self.height() / 2)
    }

    /// Returns an iterator of slices representing the pixels of the image.
    /// Each slice in the Vec is a row. The returned slice should be of ``Vec<&[P; width]>``.
    #[inline]
    pub fn pixels(&self) -> impl Iterator<Item = &[P]> {
        self.data.chunks_exact(self.width() as usize)
    }

    /// Returns the encoding format of the image. This is nothing more but metadata about the image.
    /// When saving the image, you will still have to explicitly specify the encoding format.
    #[inline]
    #[must_use]
    pub const fn format(&self) -> ImageFormat {
        self.format
    }

    /// Returns the overlay mode of the image.
    #[inline]
    #[must_use]
    pub const fn overlay_mode(&self) -> OverlayMode {
        self.overlay
    }

    /// Returns the same image with its overlay mode set to the given value.
    #[must_use]
    pub const fn with_overlay_mode(mut self, mode: OverlayMode) -> Self {
        self.overlay = mode;
        self
    }

    /// Returns the dimensions of the image.
    #[inline]
    #[must_use]
    pub const fn dimensions(&self) -> (u32, u32) {
        (self.width(), self.height())
    }

    /// Returns the amount of pixels in the image.
    #[inline]
    #[must_use]
    pub const fn len(&self) -> u32 {
        self.width() * self.height()
    }

    /// Returns true if the image contains no pixels.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reference of the pixel at the given coordinates.
    #[inline]
    #[must_use]
    pub fn pixel(&self, x: u32, y: u32) -> &P {
        &self.data[self.resolve_coordinate(x, y)]
    }

    /// Returns a reference of the pixel at the given coordinates, but only if it exists.
    #[inline]
    #[must_use]
    pub fn get_pixel(&self, x: u32, y: u32) -> Option<&P> {
        self.data.get(self.resolve_coordinate(x, y))
    }

    /// Returns a mutable reference to the pixel at the given coordinates.
    #[inline]
    pub fn pixel_mut(&mut self, x: u32, y: u32) -> &mut P {
        let pos = self.resolve_coordinate(x, y);

        &mut self.data[pos]
    }

    /// Sets the pixel at the given coordinates to the given pixel.
    #[inline]
    pub fn set_pixel(&mut self, x: u32, y: u32, pixel: P) {
        let pos = self.resolve_coordinate(x, y);

        self.data[pos] = pixel;
    }

    /// Overlays the pixel at the given coordinates with the given pixel according to the overlay
    /// mode.
    #[inline]
    pub fn overlay_pixel(&mut self, x: u32, y: u32, pixel: P) {
        self.overlay_pixel_with_mode(x, y, pixel, self.overlay);
    }

    /// Overlays the pixel at the given coordinates with the given pixel according to the specified
    /// overlay mode.
    ///
    /// If the pixel is out of bounds, nothing occurs: the method will fail silently.
    /// This is expected, use [`Self::set_pixel`] if you want this to panic, or to use a custom
    /// overlay mode use [`Self::pixel_mut`].
    #[inline]
    pub fn overlay_pixel_with_mode(&mut self, x: u32, y: u32, pixel: P, mode: OverlayMode) {
        let pos = self.resolve_coordinate(x, y);

        if let Some(target) = self.data.get_mut(pos) {
            *target = target.overlay(pixel, mode);
        }
    }

    /// Overlays the pixel at the given coordinates with the given alpha intensity. This does not
    /// regard the overlay mode, since this is usually used for anti-aliasing.
    ///
    /// If the pixel is out of bounds, nothing occurs: this method will fail silently.
    /// This is expected, use [`Self::set_pixel`] if you want this to panic, or to use a custom
    /// overlay mode use [`Self::pixel_mut`].
    #[inline]
    pub fn overlay_pixel_with_alpha(
        &mut self,
        x: u32,
        y: u32,
        pixel: P,
        mode: OverlayMode,
        alpha: u8,
    ) {
        let pos = self.resolve_coordinate(x, y);

        if let Some(target) = self.data.get_mut(pos) {
            *target = target.overlay_with_alpha(pixel, mode, alpha);
        }
    }

    /// Inverts this image in place.
    ///
    /// Equivalent to:
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() {
    /// # let mut image = Image::<Rgb>::new(1, 1, Rgb::black());
    /// image.map_in_place(|_x, _y, pixel| *pixel = !*pixel);
    /// # }
    pub fn invert(&mut self) {
        self.data.iter_mut().for_each(|p| *p = !*p);
    }

    /// Takes this image and inverts it. Useful for method chaining.
    #[must_use]
    #[deprecated(note = "use the `Not` trait instead (e.g. `!image`)")]
    pub fn inverted(self) -> Self {
        self.map_pixels(|pixel| !pixel)
    }

    /// Brightens the image by increasing all pixels by the specified amount of subpixels in place.
    /// See [`Self::darken`] to darken the image, since this usually does not take any negative
    /// values.
    ///
    /// A subpixel is a value of a pixel's component, for example in RGB, each subpixel is a value
    /// of either R, G, or B.
    ///
    /// For anything with alpha, alpha is not brightened.
    pub fn brighten(&mut self, amount: P::Subpixel)
    where
        P::Subpixel: SaturatingAdd + Copy,
    {
        self.data
            .iter_mut()
            .for_each(|p| *p = p.map_subpixels(|value| value.saturating_add(&amount), |a| a));
    }

    /// Darkens the image by decreasing all pixels by the specified amount of subpixels in place.
    /// See [`Self::brighten`] to brighten the image, since this usually does not take any negative
    /// values.
    ///
    /// A subpixel is a value of a pixel's component, for example in RGB, each subpixel is a value
    /// of either R, G, or B.
    ///
    /// For anything with alpha, alpha is not brightened.
    pub fn darken(&mut self, amount: P::Subpixel)
    where
        P::Subpixel: SaturatingSub + Copy,
    {
        self.data
            .iter_mut()
            .for_each(|p| *p = p.map_subpixels(|value| value.saturating_sub(&amount), |a| a));
    }

    /// Takes this image and brightens it by increasing all pixels by the specified amount of
    /// subpixels. Negative values will darken the image. Useful for method chaining.
    ///
    /// See [`Self::darkened`] to darken the image, since this usually does not take any negative
    /// values.
    ///
    /// A subpixel is a value of a pixel's component, for example in RGB, each subpixel is a value.
    ///
    /// For anything with alpha, alpha is not brightened.
    #[must_use]
    pub fn brightened(self, amount: P::Subpixel) -> Self
    where
        P::Subpixel: SaturatingAdd + Copy,
    {
        self.map_pixels(|pixel| pixel.map_subpixels(|value| value.saturating_add(&amount), |a| a))
    }

    /// Takes this image and darkens it by decreasing all pixels by the specified amount of
    /// subpixels. Negative values will brighten the image. Useful for method chaining.
    ///
    /// See [`Self::brightened`] to brighten the image, since this usually does not take any
    /// negative values.
    ///
    /// A subpixel is a value of a pixel's component, for example in RGB, each subpixel is a value.
    ///
    /// For anything with alpha, alpha is not brightened.
    #[must_use]
    pub fn darkened(self, amount: P::Subpixel) -> Self
    where
        P::Subpixel: SaturatingSub + Copy,
    {
        self.map_pixels(|pixel| pixel.map_subpixels(|value| value.saturating_sub(&amount), |a| a))
    }

    #[allow(clippy::cast_lossless)]
    fn prepare_hue_matrix(degrees: i32) -> (f64, f64, f64, f64, f64, f64, f64, f64, f64) {
        let degrees = (degrees % 360) as f64;
        let radians = degrees.to_radians();
        let sinv = radians.sin();
        let cosv = radians.cos();

        (
            sinv.mul_add(-0.213, cosv.mul_add(0.787, 0.213)),
            sinv.mul_add(-0.715, cosv.mul_add(-0.715, 0.715)),
            sinv.mul_add(0.928, cosv.mul_add(-0.072, 0.072)),
            sinv.mul_add(0.143, cosv.mul_add(-0.213, 0.213)),
            sinv.mul_add(0.140, cosv.mul_add(0.285, 0.715)),
            sinv.mul_add(-0.283, cosv.mul_add(-0.072, 0.072)),
            sinv.mul_add(-0.787, cosv.mul_add(-0.213, 0.213)),
            sinv.mul_add(0.715, cosv.mul_add(-0.715, 0.715)),
            sinv.mul_add(0.072, cosv.mul_add(0.928, 0.072)),
        )
    }

    /// Hue rotates the image by the specified amount of degrees in place.
    ///
    /// The hue is a standard angle degree, that is a value between 0 and 360, although values
    /// below and above will be wrapped using the modulo operator.
    ///
    /// For anything with alpha, alpha is not rotated.
    pub fn hue_rotate(&mut self, degrees: i32)
    where
        P: TrueColor,
    {
        let mat = Self::prepare_hue_matrix(degrees);

        self.data.iter_mut().for_each(|p| {
            let (r, g, b, a) = p.as_rgba_tuple();
            let (r, g, b) = (f64::from(r), f64::from(g), f64::from(b));

            *p = P::from_rgba_tuple((
                mat.2.mul_add(b, mat.0.mul_add(r, mat.1 * g)) as u8,
                mat.5.mul_add(b, mat.3.mul_add(r, mat.4 * g)) as u8,
                mat.8.mul_add(b, mat.6.mul_add(r, mat.7 * g)) as u8,
                a,
            ));
        });
    }

    /// Takes this image and hue rotates it by the specified amount of degrees.
    /// Useful for method chaining.
    ///
    /// See [`Self::hue_rotate`] for more information.
    #[must_use]
    pub fn hue_rotated(mut self, degrees: i32) -> Self
    where
        P: TrueColor,
    {
        self.hue_rotate(degrees);
        self
    }

    /// Returns the image replaced with the given data. It is up to you to make sure
    /// the data is the correct size.
    ///
    /// The function should take the current image data and return the new data.
    ///
    /// # Note
    /// This will *not* work for paletted images, nor will it work for conversion to paletted
    /// images. For conversion from paletted images, see the [`Self::flatten`] method to flatten
    /// the palette fist. For conversion to paletted images, try quantizing the image.
    pub fn map_data<T: Pixel>(self, f: impl FnOnce(Vec<P>) -> Vec<T>) -> Image<T> {
        Image {
            width: self.width,
            height: self.height,
            data: f(self.data),
            format: self.format,
            overlay: self.overlay,
            palette: None,
        }
    }

    /// Sets the data of this image to the new data. This is used a lot internally,
    /// but should rarely be used by you.
    ///
    /// # Panics
    /// * Panics if the data is malformed.
    pub fn set_data(&mut self, data: Vec<P>) {
        assert_eq!(
            self.width() * self.height(),
            data.len() as u32,
            "malformed data"
        );

        self.data = data;
    }

    /// Returns the image with each pixel in the image mapped to the given function.
    ///
    /// The function should take the pixel and return another pixel.
    pub fn map_pixels<T: Pixel>(self, f: impl FnMut(P) -> T) -> Image<T> {
        self.map_data(|data| data.into_iter().map(f).collect())
    }

    /// Returns the image with the each pixel in the image mapped to the given function, with
    /// the function taking additional data of the pixel.
    ///
    /// The function should take the x and y coordinates followed by the pixel and return the new
    /// pixel.
    pub fn map_pixels_with_coords<T: Pixel>(self, f: impl Fn(u32, u32, P) -> T) -> Image<T> {
        let width = self.width;

        self.map_data(|data| {
            data.into_iter()
                .zip(0..)
                .map(|(p, i)| f(i % width, i / width, p))
                .collect()
        })
    }

    pub(crate) fn map_image_with_coords<T: Pixel>(
        self,
        f: impl Fn(&Self, u32, u32, P) -> T,
    ) -> Image<T> {
        let width = self.width;

        let data = self
            .data
            .iter()
            .zip(0..)
            .map(|(p, i)| f(&self, i % width, i / width, *p))
            .collect();

        Image {
            width: self.width,
            height: self.height,
            data,
            format: self.format,
            overlay: self.overlay,
            palette: None,
        }
    }

    /// Similar to [`Self::map_pixels_with_coords`], but this maps the pixels in place.
    ///
    /// This means that the output pixel type must be the same.
    pub fn map_in_place(&mut self, f: impl Fn(u32, u32, &mut P)) {
        let width = self.width;

        self.data
            .iter_mut()
            .zip(0..)
            .for_each(|(p, i)| f(i % width, i / width, p));
    }

    /// Returns the image with each row of pixels represented as a slice mapped to the given
    /// function.
    ///
    /// The function should take the y coordinate followed by the row of pixels
    /// (represented as a slice) and return an Iterator of pixels.
    pub fn map_rows<I, T: Pixel>(self, f: impl Fn(u32, &[P]) -> I) -> Image<T>
    where
        I: IntoIterator<Item = T>,
    {
        let width = self.width();

        self.map_data(|data| {
            data.chunks(width as usize)
                .zip(0..)
                .flat_map(|(row, y)| f(y, row))
                .collect()
        })
    }

    /// Iterates over each row of pixels in the image.
    pub fn rows(&self) -> impl Iterator<Item = &[P]> {
        self.data.chunks_exact(self.width() as usize)
    }

    /// Converts the image into an image with the given pixel type.
    ///
    /// # Note
    /// Currently there is a slight inconsistency with paletted images - if you would like to
    /// convert from a paletted image to a paletted image with a different pixel type, you cannot
    /// use this method and must instead use the `From`/`Into` trait instead.
    ///
    /// That said, you can also use the `From`/`Into` trait regardless of the pixel type.
    #[must_use]
    pub fn convert<T: Pixel + From<P>>(self) -> Image<T> {
        self.map_pixels(T::from)
    }

    /// Sets the encoding format of this image. Note that when saving the file,
    /// an encoding format will still have to be explicitly specified.
    /// This is more or less image metadata.
    pub fn set_format(&mut self, format: ImageFormat) {
        self.format = format;
    }

    /// Crops this image in place to the given bounding box.
    ///
    /// # Panics
    /// * The width or height of the bounding box is less than 1.
    pub fn crop(&mut self, x1: u32, y1: u32, x2: u32, y2: u32) {
        self.data = self
            .pixels()
            .skip(y1 as usize)
            .zip(y1..y2)
            .flat_map(|(row, _)| &row[x1 as usize..x2 as usize])
            .copied()
            .collect();

        self.width = NonZeroU32::new(x2 - x1).unwrap();
        self.height = NonZeroU32::new(y2 - y1).unwrap();
    }

    /// Takes this image and crops it to the given box. Useful for method chaining.
    #[must_use]
    pub fn cropped(mut self, x1: u32, y1: u32, x2: u32, y2: u32) -> Self {
        self.crop(x1, y1, x2, y2);
        self
    }

    /// Mirrors, or flips this image horizontally (about the y-axis) in place.
    pub fn mirror(&mut self) {
        let width = self.width();

        self.data
            .chunks_exact_mut(width as usize)
            .for_each(<[P]>::reverse);
    }

    /// Takes this image and flips it horizontally (about the y-axis). Useful for method chaining.
    #[must_use]
    pub fn mirrored(mut self) -> Self {
        self.mirror();
        self
    }

    /// Flips this image vertically (about the x-axis) in place.
    pub fn flip(&mut self) {
        self.mirror();
        self.rotate_180();
    }

    /// Takes this image and flips it vertically, or about the x-axis. Useful for method chaining.
    #[must_use]
    pub fn flipped(mut self) -> Self {
        self.flip();
        self
    }

    fn rotate_iterator(&self) -> impl DoubleEndedIterator<Item = P> + '_ {
        (0..self.width() as usize).flat_map(move |i| {
            (0..self.height() as usize)
                .map(move |j| self.data[j * self.width() as usize + i])
                .rev()
        })
    }

    /// Rotates this image by 90 degrees clockwise, or 270 degrees counterclockwise, in place.
    ///
    /// # See Also
    /// - [`Self::rotate`] for a version that can take any arbitrary amount of degrees
    /// - [`Self::rotated`] for the above method which does operate in-place - useful for method
    ///   chaining
    pub fn rotate_90(&mut self) {
        self.data = self.rotate_iterator().collect();
        std::mem::swap(&mut self.width, &mut self.height);
    }

    /// Rotates this image by 180 degrees in place.
    ///
    /// # See Also
    /// - [`Self::rotate`] for a version that can take any arbitrary amount of degrees
    /// - [`Self::rotated`] for the above method which does operate in-place - useful for method
    ///   chaining
    pub fn rotate_180(&mut self) {
        self.data.reverse();
    }

    /// Rotates this image by 270 degrees clockwise, or 90 degrees counterclockwise, in place.
    ///
    /// # See Also
    /// - [`Self::rotate`] for a version that can take any arbitrary amount of degrees
    /// - [`Self::rotated`] for the above method which does operate in-place - useful for method
    /// chaining
    pub fn rotate_270(&mut self) {
        self.data = self.rotate_iterator().rev().collect();
        std::mem::swap(&mut self.width, &mut self.height);
    }

    /// Rotates this image in place about its center. There are optimized rotating algorithms for
    /// 90, 180, and 270 degree rotations (clockwise).
    ///
    /// As mentioned, the argument is specified in degrees.
    ///
    /// # See Also
    /// - [`Self::rotated`] for this method which does operate in-place - useful for method chaining
    pub fn rotate(&mut self, mut degrees: i32) {
        degrees %= 360;

        match degrees {
            0 => (),
            90 => self.rotate_90(),
            180 => self.rotate_180(),
            270 => self.rotate_270(),
            _ => unimplemented!(
                "currently only rotations of 0, 90, 180, and 270 degrees are supported",
            ),
        }
    }

    /// Takes the image and rotates it by the specified amount of degrees about its center. Useful
    /// for method chaining. There are optimized rotating algorithms for 90, 180, and 270 degree
    /// rotations.
    #[must_use]
    pub fn rotated(mut self, degrees: i32) -> Self {
        self.rotate(degrees);
        self
    }

    /// Resizes this image in place to the given dimensions using the given resizing algorithm
    /// in place.
    ///
    /// `width` and `height` must be greater than 0, otherwise this method will panic. You should
    /// validate user input before calling this method.
    ///
    /// # Panics
    /// * `width` or `height` is zero.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let mut image = Image::new(256, 256, Rgb::white());
    /// assert_eq!(image.dimensions(), (256, 256));
    ///
    /// image.resize(64, 64, ResizeAlgorithm::Lanczos3);
    /// assert_eq!(image.dimensions(), (64, 64));
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "resize")]
    pub fn resize(&mut self, width: u32, height: u32, algorithm: ResizeAlgorithm) {
        assert_nonzero!(width, height);

        let width = NonZeroU32::new(width).unwrap();
        let height = NonZeroU32::new(height).unwrap();

        self.data = crate::resize::resize(
            &self.data,
            self.width.get(),
            self.height.get(),
            width.get(),
            height.get(),
            algorithm,
        );
        self.width = width;
        self.height = height;
    }

    /// Takes this image and resizes this image to the given dimensions using the given
    /// resizing algorithm. Useful for method chaining.
    ///
    /// `width` and `height` must be greater than 0, otherwise this method will panic. You should
    /// validate user input before calling this method.
    ///
    /// # Panics
    /// * `width` or `height` is zero.
    ///
    /// # See Also
    /// * [`Self::resize`] for a version that operates in-place
    #[must_use]
    #[cfg(feature = "resize")]
    pub fn resized(mut self, width: u32, height: u32, algorithm: ResizeAlgorithm) -> Self {
        self.resize(width, height, algorithm);
        self
    }

    /// Draws an object or shape onto this image.
    ///
    /// # Example
    /// ```
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let mut image = Image::new(256, 256, Rgb::white());
    /// let rectangle = Rectangle::at(64, 64)
    ///     .with_size(128, 128)
    ///     .with_fill(Rgb::black());
    ///
    /// image.draw(&rectangle);
    /// # Ok(())
    /// # }
    /// ```
    pub fn draw(&mut self, entity: &impl Draw<P>) {
        entity.draw(self);
    }

    /// Takes this image, draws the given object or shape onto it, and returns it.
    /// Useful for method chaining and drawing multiple objects at once.
    ///
    /// # See Also
    /// * [`Self::draw`] for a version that operates in-place
    #[must_use]
    pub fn with(mut self, entity: &impl Draw<P>) -> Self {
        self.draw(entity);
        self
    }

    /// Pastes the given image onto this image at the given x and y coordinates.
    /// This is a shorthand for using the [`Self::draw`] method with [`crate::Paste`].
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let mut image = Image::new(256, 256, Rgb::white());
    /// let overlay_image = Image::open("overlay.png")?;
    ///
    /// image.paste(64, 64, &overlay_image);
    /// # Ok(())
    /// # }
    /// ```
    pub fn paste(&mut self, x: u32, y: u32, image: &Self) {
        self.draw(&crate::Paste::new(image).with_position(x, y));
    }

    /// Pastes the given image onto this image at the given x and y coordinates,
    /// masked with the given masking image.
    ///
    /// Currently, only [`BitPixel`] images are supported for the masking image.
    ///
    /// This is a shorthand for using the [`Self::draw`] method with [`crate::Paste`].
    ///
    /// # Example
    /// ```no_run
    /// # use ril::prelude::*;
    /// # fn main() -> ril::Result<()> {
    /// let mut image = Image::new(256, 256, Rgb::white());
    /// let overlay_image = Image::open("overlay.png")?;
    ///
    /// let (w, h) = overlay_image.dimensions();
    /// let mut mask = Image::new(w, h, BitPixel::off());
    /// mask.draw(&Ellipse::from_bounding_box(0, 0, w, h).with_fill(BitPixel::on()));
    ///
    /// image.paste_with_mask(64, 64, &overlay_image, &mask);
    /// # Ok(())
    /// # }
    /// ```
    pub fn paste_with_mask(&mut self, x: u32, y: u32, image: &Self, mask: &Image<BitPixel>) {
        self.draw(&crate::Paste::new(image).with_position(x, y).with_mask(mask));
    }

    /// Masks the alpha values of this image with the luminance values of the given single-channel
    /// [`L`] image.
    ///
    /// If you want to mask using the alpha values of the image instead of providing an [`L`] image,
    /// you can split the bands of the image and extract the alpha band.
    ///
    /// This masking image must have the same dimensions as this image. If it doesn't, you will
    /// receive a panic.
    ///
    /// # Panics
    /// * The masking image has different dimensions from this image.
    pub fn mask_alpha(&mut self, mask: &Image<L>)
    where
        P: Alpha,
    {
        assert_eq!(
            self.dimensions(),
            mask.dimensions(),
            "Masking image with dimensions {:?} must have the \
            same dimensions as this image with dimensions {:?}",
            mask.dimensions(),
            self.dimensions()
        );

        self.data
            .iter_mut()
            .zip(mask.data.iter())
            .for_each(|(pixel, mask)| {
                *pixel = pixel.with_alpha(mask.value());
            });
    }

    /// Returns the palette associated with this image as a slice.
    /// If there is no palette, this returns `None`.
    #[must_use]
    pub fn palette(&self) -> Option<&[P::Color]> {
        self.palette.as_deref()
    }

    /// Returns the palette associated with this image as a mutable slice.
    /// If there is no palette, this returns `None`.
    #[must_use]
    pub fn palette_mut(&mut self) -> Option<&mut [P::Color]> {
        self.palette.as_deref_mut()
    }

    /// Returns the palette associated with this image as a slice. You must uphold the guarantee
    /// that the image is paletted, otherwise this will result in undefined behaviour.
    ///
    /// # Safety
    /// * The image must always be paletted.
    ///
    /// # See Also
    /// * [`Self::palette`] - A safe, checked alternative to this method.
    #[must_use]
    pub unsafe fn palette_unchecked(&self) -> &[P::Color] {
        self.palette.as_ref().unwrap_unchecked()
    }

    /// Returns the palette associated with this image as a mutable slice. You must uphold the
    /// guarantee that the image is paletted, otherwise this will result in undefined behaviour.
    ///
    /// # Safety
    /// * The image must always be paletted.
    ///
    /// # See Also
    /// * [`Self::palette_mut`] - A safe, checked alternative to this method.
    #[must_use]
    pub unsafe fn palette_mut_unchecked(&mut self) -> &mut [P::Color] {
        self.palette.as_mut().unwrap_unchecked()
    }

    /// Maps the palette of this image using the given function. If this image has no palette,
    /// this will do nothing.
    ///
    /// # Panics
    /// * Safe conversion of palette references failed.
    pub fn map_palette<'a, U, F, C: TrueColor>(self, mut f: F) -> Image<U>
    where
        Self: 'a,
        P: Paletted<'a>,
        U: Paletted<'a> + Pixel<Subpixel = P::Subpixel, Color = C>,
        F: FnMut(P::Color) -> C,
    {
        let palette = self.palette.map(|palette| {
            palette
                .iter()
                .map(|p| f(*p))
                .collect::<Vec<_>>()
                .into_boxed_slice()
        });

        Image {
            width: self.width,
            height: self.height,
            data: self
                .data
                .into_iter()
                .map(|p| {
                    U::from_raw_parts_paletted(
                        U::COLOR_TYPE,
                        U::BIT_DEPTH,
                        &[p.palette_index().into() as u8],
                        palette.as_deref(),
                    )
                    .expect("could not perform safe conversion of palette references")
                })
                .collect(),
            format: self.format,
            overlay: self.overlay,
            palette,
        }
    }

    /// Takes this image and flattens this paletted image into an unpaletted image. This is similar
    /// to [`Self::convert`] but the output type is automatically resolved.
    #[must_use = "the image is consumed by this method and returns a new image"]
    pub fn flatten_palette<'a>(self) -> Image<P::Color>
    where
        Self: 'a,
        P: Paletted<'a>,
    {
        self.map_pixels(|pixel| pixel.color())
    }

    /// Quantizes this image using its colors and turns it into its paletted counterpart.
    /// This currently only works with 8-bit palettes.
    ///
    /// This is similar to [`Self::convert`] but the output type is automatically resolved.
    /// This is also the inverse conversion of [`Self::flatten_palette`].
    ///
    /// # Errors
    /// * The palette could not be created.
    ///
    /// # Panics
    /// * Unable to quantize the image.
    ///
    /// # See Also
    /// * [`Quantizer`] - Implementation of the core quantizer. Use this for more fine-grained
    ///   control over the quantization process, such as adjusting the quantization speed.
    #[must_use = "the image is consumed by this method and returns a new image"]
    pub fn quantize<'p, T>(self, palette_size: u8) -> Image<T>
    where
        Self: 'p,
        P: TrueColor,
        T: Pixel<Color = P> + Paletted<'p, Subpixel = u8>,
    {
        let width = self.width();
        let (palette, pixels) = crate::quantize::Quantizer::new()
            .with_palette_size(palette_size as usize)
            .quantize(self.data)
            .expect("unable to quantize image");

        Image::from_paletted_pixels(width, palette, pixels)
    }
}

impl Image<Rgba> {
    /// Splits this image into an `Rgb` image and an `L` image, where the `Rgb` image contains the
    /// red, green, and blue color channels and the `L` image contains the alpha channel.
    ///
    /// There is a more optimized method available, [`Self::map_rgb_pixels`], if you only need to perform
    /// operations on individual RGB pixels. If you can, you should use that instead.
    ///
    /// # Example
    /// Rotating the image by 90 degrees but keeping the alpha channel untouched:
    ///
    /// ```no_run
    /// use ril::prelude::*;
    ///
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::<Rgba>::open("image.png")?;
    /// let (rgb, alpha) = image.split_rgb_and_alpha();
    /// let inverted = Image::from_rgb_and_alpha(rgb.rotated(90), alpha);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # See Also
    /// * [`Self::from_rgb_and_alpha`] - The inverse of this method.
    /// * [`Self::map_rgb_pixels`] - A more optimized method for performing operations on individual RGB
    ///   pixels.
    #[must_use]
    pub fn split_rgb_and_alpha(self) -> (Image<Rgb>, Image<L>) {
        let (r, g, b, a) = self.bands();
        (Image::from_bands((r, g, b)), a)
    }

    /// Creates an `Rgba` image from an `Rgb` image and an `L` image, where the `Rgb` image contains
    /// the red, green, and blue color channels and the `L` image contains the alpha channel.
    ///
    /// # Panics
    /// * The dimensions of the two images do not match.
    ///
    /// # See Also
    /// * [`Self::split_rgb_and_alpha`] - The inverse of this method.
    #[must_use]
    pub fn from_rgb_and_alpha(rgb: Image<Rgb>, alpha: Image<L>) -> Self {
        debug_assert_eq!(
            rgb.dimensions(),
            alpha.dimensions(),
            "dimensions of RGB and alpha images do not match",
        );
        rgb.map_data(|data| {
            data.into_iter()
                .zip(alpha.data)
                .map(|(Rgb { r, g, b }, L(a))| Rgba { r, g, b, a })
                .collect()
        })
    }

    /// Performs the given operation `f` on every pixel in this image, ignoring the alpha channel.
    /// The alpha channel is left untouched.
    ///
    /// # Example
    /// Inverting the image but keeping the alpha channel untouched:
    ///
    /// ```no_run
    /// use ril::prelude::*;
    ///
    /// # fn main() -> ril::Result<()> {
    /// let image = Image::<Rgba>::open("image.png")?;
    /// let inverted = image.map_rgb_pixels(|rgb| !rgb);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # See Also
    /// * [`Self::map_alpha_pixels`] - Performs the given operation on every pixel in the alpha
    ///   channel.
    /// * [`Self::split_rgb_and_alpha`] - If you need to operate on the entire `Image<Rgb>`
    ///   (and `Image<L>`).
    #[must_use]
    pub fn map_rgb_pixels(self, mut f: impl FnMut(Rgb) -> Rgb) -> Self {
        self.map_pixels(|Rgba { r, g, b, a }| {
            let Rgb { r, g, b } = f(Rgb { r, g, b });
            Rgba { r, g, b, a }
        })
    }

    /// Performs the given operation `f` on every pixel in the alpha channel of this image.
    /// The RGB channels are left untouched.
    ///
    /// # See Also
    /// * [`Self::map_rgb_pixels`] - Performs the given operation on every pixel in the RGB channels.
    /// * [`Self::split_rgb_and_alpha`] - If you need to operate on the entire `Image<L>`
    ///   (and `Image<Rgb>`).
    #[must_use]
    pub fn map_alpha_pixels(self, mut f: impl FnMut(L) -> L) -> Self {
        self.map_pixels(|Rgba { r, g, b, a }| Rgba {
            r,
            g,
            b,
            a: f(L(a)).value(),
        })
    }
}

impl<'a> From<Image<PalettedRgb<'a>>> for Image<PalettedRgba<'a>> {
    fn from(image: Image<PalettedRgb<'a>>) -> Self {
        image.map_palette(Into::into)
    }
}

impl<'a> From<Image<PalettedRgba<'a>>> for Image<PalettedRgb<'a>> {
    fn from(image: Image<PalettedRgba<'a>>) -> Self {
        image.map_palette(Into::into)
    }
}

macro_rules! impl_cast_quantize {
    ($t:ty: $p:ty) => {
        impl From<Image<$t>> for Image<$p> {
            fn from(image: Image<$t>) -> Self {
                let width = image.width();
                let (palette, pixels) = crate::quantize::Quantizer::new()
                    .with_palette_size(image.data.len())
                    .quantize(image.data)
                    .expect("unable to quantize image");

                Image::from_paletted_pixels(width, palette, pixels)
            }
        }
    };
}

impl_cast_quantize!(Rgb: PalettedRgb<'_>);
impl_cast_quantize!(Rgba: PalettedRgba<'_>);

macro_rules! impl_cast {
    ($t:ty: $($f:ty)+) => {
        $(
            impl From<Image<$f>> for Image<$t> {
                fn from(f: Image<$f>) -> Self {
                    f.map_pixels(<$t>::from)
                }
            }
        )+
    };
}

impl_cast!(BitPixel: L Rgb Rgba Dynamic PalettedRgb<'_> PalettedRgba<'_>);
impl_cast!(L: BitPixel Rgb Rgba Dynamic PalettedRgb<'_> PalettedRgba<'_>);
impl_cast!(Rgb: BitPixel L Rgba Dynamic PalettedRgb<'_> PalettedRgba<'_>);
impl_cast!(Rgba: BitPixel L Rgb Dynamic PalettedRgb<'_> PalettedRgba<'_>);
impl_cast!(Dynamic: BitPixel L Rgb Rgba PalettedRgb<'_> PalettedRgba<'_>);

/// Represents an image with multiple channels, called bands.
///
/// Each band should be represented as a separate [`Image`] with [`L`] or [`BitPixel`] pixels.
pub trait Banded<T> {
    /// Takes this image and returns its bands.
    fn bands(&self) -> T;

    /// Creates a new image from the given bands.
    fn from_bands(bands: T) -> Self;
}

type Band = Image<L>;

macro_rules! map_idx {
    ($image:expr, $idx:expr) => {{
        use $crate::{Image, L};

        Image {
            width: $image.width,
            height: $image.height,
            data: $image.data.iter().map(|p| L(p.as_bytes()[$idx])).collect(),
            format: $image.format,
            overlay: $image.overlay,
            palette: None,
        }
    }};
}

macro_rules! extract_bands {
    ($image:expr; $($idx:literal)+) => {{
        ($(map_idx!($image, $idx)),+)
    }};
}

macro_rules! validate_dimensions {
    ($target:ident, $($others:ident),+) => {{
        $(
            assert_eq!(
                $target.dimensions(),
                $others.dimensions(),
                "bands have different dimensions: {} has dimensions of {:?}, which is different \
                from {} which has dimenesions of {:?}",
                stringify!($target),
                $target.dimensions(),
                stringify!($others),
                $others.dimensions()
            );
        )+
    }};
}

impl Banded<(Band, Band, Band)> for Image<Rgb> {
    fn bands(&self) -> (Band, Band, Band) {
        extract_bands!(self; 0 1 2)
    }

    fn from_bands((r, g, b): (Band, Band, Band)) -> Self {
        validate_dimensions!(r, g, b);

        r.map_data(|data| {
            data.into_iter()
                .zip(g.data)
                .zip(b.data)
                .map(|((L(r), L(g)), L(b))| Rgb::new(r, g, b))
                .collect()
        })
    }
}

impl Banded<(Band, Band, Band, Band)> for Image<Rgba> {
    fn bands(&self) -> (Band, Band, Band, Band) {
        extract_bands!(self; 0 1 2 3)
    }

    fn from_bands((r, g, b, a): (Band, Band, Band, Band)) -> Self {
        validate_dimensions!(r, g, b, a);

        r.map_data(|data| {
            data.into_iter()
                .zip(g.data)
                .zip(b.data)
                .zip(a.data)
                .map(|(((L(r), L(g)), L(b)), L(a))| Rgba::new(r, g, b, a))
                .collect()
        })
    }
}

impl<P: Pixel> std::ops::Not for Image<P> {
    type Output = Self;

    fn not(self) -> Self::Output {
        self.map_pixels(|p| !p)
    }
}