1
//! Image decoding and encoding utilities, wrapping the `image` crate
2
//! with Azul's FFI-compatible types (`RawImage`, `RawImageFormat`).
3
//!
4
//! - [`decode`]: Decodes image bytes in any supported format into a [`RawImage`].
5
//! - [`encode`]: Encodes a [`RawImage`] into various output formats (PNG, JPEG, BMP, etc.).
6

            
7
#[cfg(feature = "std")]
8
pub mod decode {
9
    use core::fmt;
10

            
11
    use azul_core::resources::{RawImage, RawImageFormat};
12
    use azul_css::{impl_option, impl_option_inner, impl_result, impl_result_inner, U8Vec};
13
    use image::{
14
        error::{ImageError, LimitError, LimitErrorKind},
15
        DynamicImage,
16
    };
17

            
18
    /// Errors that can occur when decoding an image from raw bytes.
19
    #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
20
    #[repr(C)]
21
    pub enum DecodeImageError {
22
        InsufficientMemory,
23
        DimensionError,
24
        UnsupportedImageFormat,
25
        Unknown,
26
    }
27

            
28
    impl fmt::Display for DecodeImageError {
29
24
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30
24
            match self {
31
6
                Self::InsufficientMemory => write!(
32
6
                    f,
33
6
                    "Error decoding image: Not enough memory available to perform encoding \
34
6
                     operation"
35
                ),
36
                Self::DimensionError => {
37
6
                    write!(f, "Error decoding image: Wrong dimensions")
38
                }
39
                Self::UnsupportedImageFormat => {
40
6
                    write!(f, "Error decoding image: Invalid data format")
41
                }
42
6
                Self::Unknown => write!(f, "Error decoding image: Unknown error"),
43
            }
44
24
        }
45
    }
46

            
47
283
    fn translate_image_error_decode(i: ImageError) -> DecodeImageError {
48
283
        match i {
49
3
            ImageError::Limits(l) => match l.kind() {
50
1
                LimitErrorKind::InsufficientMemory => DecodeImageError::InsufficientMemory,
51
1
                LimitErrorKind::DimensionError => DecodeImageError::DimensionError,
52
1
                _ => DecodeImageError::Unknown,
53
            },
54
280
            _ => DecodeImageError::Unknown,
55
        }
56
283
    }
57

            
58
    impl_result!(
59
        RawImage,
60
        DecodeImageError,
61
        ResultRawImageDecodeImageError,
62
        copy = false,
63
        [Debug, Clone]
64
    );
65

            
66
    /// Result of [`decode_image_bytes`] (`RawImage::decode_image_bytes` in
67
    /// the API).
68
    #[derive(Debug, Clone)]
69
    #[repr(C)]
70
    pub struct ImageDecodeResult {
71
        pub result: ResultRawImageDecodeImageError,
72
    }
73

            
74
    impl_option!(
75
        ImageDecodeResult,
76
        OptionImageDecodeResult,
77
        copy = false,
78
        [Debug, Clone]
79
    );
80

            
81
    impl ImageDecodeResult {
82
        /// Downcast the `result` `RefAny` delivered to a `ResumeCallback`.
83
        #[must_use]
84
        pub fn downcast(mut result: azul_core::refany::RefAny) -> OptionImageDecodeResult {
85
            result.downcast_ref::<Self>().map(|r| r.clone()).into()
86
        }
87
    }
88

            
89
    /// Decodes `bytes` (any supported format, guessed from the magic header)
90
    /// and resumes `on_result` with an [`ImageDecodeResult`].
91
    ///
92
    /// This is the fast path on web, where the browser's hardware decoders
93
    /// (`createImageBitmap`) do the work; on desktop it runs the same pure
94
    /// decoder as [`decode_raw_image_from_any_bytes`] and resumes right
95
    /// after the current activation returns. Decoded pixels may differ per
96
    /// backend (premultiplication, ICC handling), so treat the output as an
97
    /// RGBA bitmap, not as a byte-exact reference.
98
    #[cfg(feature = "text_layout")]
99
    #[must_use]
100
    pub fn decode_image_bytes(
101
        bytes: U8Vec,
102
        data: azul_core::refany::RefAny,
103
        on_result: crate::callbacks::ResumeCallback,
104
    ) -> azul_core::task::RequestId {
105
        let result = decode_raw_image_from_any_bytes(bytes.as_ref());
106
        crate::request::complete(data, on_result, ImageDecodeResult { result })
107
    }
108

            
109
    /// Decodes image bytes in any supported format into a [`RawImage`].
110
    ///
111
    /// The image format is guessed from the byte contents. Returns the decoded
112
    /// pixel data along with dimensions and format information. Pure
113
    /// compute: works on every target, but on web the resumable
114
    /// [`decode_image_bytes`] uses the browser's hardware decoder and is the
115
    /// faster choice for large images.
116
    #[must_use]
117
275
    pub fn decode_raw_image_from_any_bytes(image_bytes: &[u8]) -> ResultRawImageDecodeImageError {
118
        use azul_core::resources::RawImageData;
119

            
120
275
        let image_format = match image::guess_format(image_bytes) {
121
8
            Ok(o) => o,
122
267
            Err(e) => {
123
267
                return ResultRawImageDecodeImageError::Err(translate_image_error_decode(e));
124
            }
125
        };
126

            
127
8
        let decoded = match image::load_from_memory_with_format(image_bytes, image_format) {
128
            Ok(o) => o,
129
8
            Err(e) => {
130
8
                return ResultRawImageDecodeImageError::Err(translate_image_error_decode(e));
131
            }
132
        };
133

            
134
        let ((width, height), data_format, pixels) = match decoded {
135
            DynamicImage::ImageLuma8(i) => (
136
                i.dimensions(),
137
                RawImageFormat::R8,
138
                RawImageData::U8(i.into_vec().into()),
139
            ),
140
            DynamicImage::ImageLumaA8(i) => (
141
                i.dimensions(),
142
                RawImageFormat::RG8,
143
                RawImageData::U8(i.into_vec().into()),
144
            ),
145
            DynamicImage::ImageRgb8(i) => (
146
                i.dimensions(),
147
                RawImageFormat::RGB8,
148
                RawImageData::U8(i.into_vec().into()),
149
            ),
150
            DynamicImage::ImageRgba8(i) => (
151
                i.dimensions(),
152
                RawImageFormat::RGBA8,
153
                RawImageData::U8(i.into_vec().into()),
154
            ),
155
            DynamicImage::ImageLuma16(i) => (
156
                i.dimensions(),
157
                RawImageFormat::R16,
158
                RawImageData::U16(i.into_vec().into()),
159
            ),
160
            DynamicImage::ImageLumaA16(i) => (
161
                i.dimensions(),
162
                RawImageFormat::RG16,
163
                RawImageData::U16(i.into_vec().into()),
164
            ),
165
            DynamicImage::ImageRgb16(i) => (
166
                i.dimensions(),
167
                RawImageFormat::RGB16,
168
                RawImageData::U16(i.into_vec().into()),
169
            ),
170
            DynamicImage::ImageRgba16(i) => (
171
                i.dimensions(),
172
                RawImageFormat::RGBA16,
173
                RawImageData::U16(i.into_vec().into()),
174
            ),
175
            DynamicImage::ImageRgb32F(i) => (
176
                i.dimensions(),
177
                RawImageFormat::RGBF32,
178
                RawImageData::F32(i.into_vec().into()),
179
            ),
180
            DynamicImage::ImageRgba32F(i) => (
181
                i.dimensions(),
182
                RawImageFormat::RGBAF32,
183
                RawImageData::F32(i.into_vec().into()),
184
            ),
185
            _ => {
186
                return ResultRawImageDecodeImageError::Err(DecodeImageError::Unknown);
187
            }
188
        };
189

            
190
        ResultRawImageDecodeImageError::Ok(RawImage {
191
            tag: Vec::new().into(),
192
            pixels,
193
            width: width as usize,
194
            height: height as usize,
195
            premultiplied_alpha: false,
196
            data_format,
197
        })
198
275
    }
199

            
200
    #[cfg(test)]
201
    mod autotest_generated {
202
        use std::collections::BTreeSet;
203

            
204
        use image::error::{
205
            DecodingError, ImageFormatHint, ParameterError, ParameterErrorKind, UnsupportedError,
206
            UnsupportedErrorKind,
207
        };
208

            
209
        use super::*;
210

            
211
        const ALL_ERRORS: [DecodeImageError; 4] = [
212
            DecodeImageError::InsufficientMemory,
213
            DecodeImageError::DimensionError,
214
            DecodeImageError::UnsupportedImageFormat,
215
            DecodeImageError::Unknown,
216
        ];
217

            
218
        fn err_of(r: &ResultRawImageDecodeImageError) -> DecodeImageError {
219
            match r.as_result() {
220
                Ok(_) => panic!("expected Err, got Ok"),
221
                Err(e) => *e,
222
            }
223
        }
224

            
225
        // --- DecodeImageError::fmt (serializer) ---------------------------------
226

            
227
        #[test]
228
        fn display_every_variant_is_non_empty_and_unique() {
229
            let rendered = ALL_ERRORS.iter().map(|e| e.to_string()).collect::<Vec<_>>();
230
            for (e, s) in ALL_ERRORS.iter().zip(rendered.iter()) {
231
                assert!(!s.is_empty(), "empty Display for {e:?}");
232
                assert!(
233
                    s.starts_with("Error decoding image: "),
234
                    "unexpected Display prefix for {e:?}: {s}"
235
                );
236
            }
237
            let unique = rendered.iter().collect::<BTreeSet<_>>();
238
            assert_eq!(
239
                unique.len(),
240
                ALL_ERRORS.len(),
241
                "Display collides: {rendered:?}"
242
            );
243
        }
244

            
245
        #[test]
246
        fn display_text_is_stable() {
247
            assert_eq!(
248
                DecodeImageError::DimensionError.to_string(),
249
                "Error decoding image: Wrong dimensions"
250
            );
251
            assert_eq!(
252
                DecodeImageError::UnsupportedImageFormat.to_string(),
253
                "Error decoding image: Invalid data format"
254
            );
255
            assert_eq!(
256
                DecodeImageError::Unknown.to_string(),
257
                "Error decoding image: Unknown error"
258
            );
259
            // NOTE: the InsufficientMemory arm says "encoding operation" inside a *decode*
260
            // error. Pinned here because it is user-visible text, not because it is right.
261
            assert_eq!(
262
                DecodeImageError::InsufficientMemory.to_string(),
263
                "Error decoding image: Not enough memory available to perform encoding operation"
264
            );
265
        }
266

            
267
        #[test]
268
        fn display_ignores_width_and_precision_specs_without_panicking() {
269
            for e in ALL_ERRORS {
270
                // The impl writes straight to the formatter, so padding/precision are no-ops.
271
                let plain = format!("{e}");
272
                assert_eq!(format!("{e:>200}"), plain);
273
                assert_eq!(format!("{e:.1}"), plain);
274
                assert_eq!(format!("{e:^0}"), plain);
275
                assert!(!format!("{e:?}").is_empty());
276
            }
277
        }
278

            
279
        #[test]
280
        fn derived_ord_is_total_and_matches_declaration_order() {
281
            for (i, a) in ALL_ERRORS.iter().enumerate() {
282
                for (j, b) in ALL_ERRORS.iter().enumerate() {
283
                    assert_eq!(a.cmp(b), i.cmp(&j), "Ord disagrees for {a:?} vs {b:?}");
284
                    assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
285
                    assert_eq!(a == b, i == j);
286
                }
287
            }
288
        }
289

            
290
        // --- translate_image_error_decode (other) -------------------------------
291

            
292
        #[test]
293
        fn translate_maps_limit_kinds() {
294
            assert_eq!(
295
                translate_image_error_decode(ImageError::Limits(LimitError::from_kind(
296
                    LimitErrorKind::InsufficientMemory
297
                ))),
298
                DecodeImageError::InsufficientMemory
299
            );
300
            assert_eq!(
301
                translate_image_error_decode(ImageError::Limits(LimitError::from_kind(
302
                    LimitErrorKind::DimensionError
303
                ))),
304
                DecodeImageError::DimensionError
305
            );
306
            // The catch-all arm of the (non_exhaustive) LimitErrorKind match.
307
            assert_eq!(
308
                translate_image_error_decode(ImageError::Limits(LimitError::from_kind(
309
                    LimitErrorKind::Unsupported {
310
                        limits: image::Limits::default(),
311
                        supported: image::LimitSupport::default(),
312
                    }
313
                ))),
314
                DecodeImageError::Unknown
315
            );
316
        }
317

            
318
        #[test]
319
        fn translate_maps_every_other_variant_to_unknown() {
320
            let cases = vec![
321
                ImageError::IoError(std::io::Error::other("boom")),
322
                ImageError::Decoding(DecodingError::new(ImageFormatHint::Unknown, "bad chunk")),
323
                ImageError::Unsupported(UnsupportedError::from_format_and_kind(
324
                    ImageFormatHint::Unknown,
325
                    UnsupportedErrorKind::Format(ImageFormatHint::Unknown),
326
                )),
327
                // NOTE: a *parameter* dimension mismatch is NOT mapped to DimensionError --
328
                // only `Limits` errors are inspected. Pinning the lossy mapping.
329
                ImageError::Parameter(ParameterError::from_kind(
330
                    ParameterErrorKind::DimensionMismatch,
331
                )),
332
                ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::NoMoreData)),
333
            ];
334
            for c in cases {
335
                let debug = format!("{c:?}");
336
                assert_eq!(
337
                    translate_image_error_decode(c),
338
                    DecodeImageError::Unknown,
339
                    "unexpected mapping for {debug}"
340
                );
341
            }
342
        }
343

            
344
        // --- decode_raw_image_from_any_bytes (other / parser-ish) ---------------
345

            
346
        #[test]
347
        fn decode_empty_input_errors_without_panicking() {
348
            let r = decode_raw_image_from_any_bytes(&[]);
349
            assert!(r.is_err());
350
            assert_eq!(err_of(&r), DecodeImageError::Unknown);
351
        }
352

            
353
        #[test]
354
        fn decode_whitespace_and_text_bytes_error() {
355
            for input in [
356
                &b"   "[..],
357
                &b"\t\n\r\n"[..],
358
                &b"not an image at all"[..],
359
                "\u{1F600} combining a\u{0301}\u{0308}".as_bytes(),
360
                "\u{FEFF}\u{202E}\u{0000}".as_bytes(),
361
            ] {
362
                let r = decode_raw_image_from_any_bytes(input);
363
                assert!(r.is_err(), "unexpectedly decoded {input:?}");
364
                assert_eq!(err_of(&r), DecodeImageError::Unknown);
365
            }
366
        }
367

            
368
        #[test]
369
        fn decode_invalid_utf8_and_garbage_bytes_error() {
370
            for input in [
371
                &[0xFF, 0xFE, 0x00][..],
372
                &[0xFF][..],
373
                &[0x00, 0x00, 0x00, 0x00][..],
374
                &[0xC0, 0x80, 0xED, 0xA0, 0x80][..],
375
            ] {
376
                let r = decode_raw_image_from_any_bytes(input);
377
                assert!(r.is_err(), "unexpectedly decoded {input:?}");
378
                assert_eq!(err_of(&r), DecodeImageError::Unknown);
379
            }
380
        }
381

            
382
        #[test]
383
        fn decode_every_single_byte_input_errors() {
384
            for b in 0u8..=255 {
385
                let r = decode_raw_image_from_any_bytes(&[b]);
386
                assert!(r.is_err(), "single byte {b:#04X} decoded to an image");
387
            }
388
        }
389

            
390
        #[test]
391
        fn decode_extremely_long_garbage_does_not_hang_or_panic() {
392
            let huge = vec![0xAAu8; 1_000_000];
393
            let r = decode_raw_image_from_any_bytes(&huge);
394
            assert!(r.is_err());
395
            assert_eq!(err_of(&r), DecodeImageError::Unknown);
396
        }
397

            
398
        /// Valid magic bytes with a truncated / missing body: `guess_format` succeeds,
399
        /// the actual decode must then fail cleanly (never panic), regardless of which
400
        /// codec features are compiled in.
401
        #[test]
402
        fn decode_valid_magic_with_no_payload_errors() {
403
            let png_magic = b"\x89PNG\r\n\x1a\n";
404
            let gif_magic = b"GIF89a";
405
            let bmp_magic = b"BM";
406
            let jpeg_magic = b"\xFF\xD8\xFF";
407

            
408
            for magic in [
409
                &png_magic[..],
410
                &gif_magic[..],
411
                &bmp_magic[..],
412
                &jpeg_magic[..],
413
            ] {
414
                let mut bytes = magic.to_vec();
415
                let r = decode_raw_image_from_any_bytes(&bytes);
416
                assert!(r.is_err(), "header-only input decoded: {magic:?}");
417

            
418
                // ... and with a garbage payload appended.
419
                bytes.extend(core::iter::repeat_n(0x7Fu8, 512));
420
                let r = decode_raw_image_from_any_bytes(&bytes);
421
                assert!(r.is_err(), "header + garbage decoded: {magic:?}");
422
            }
423
        }
424

            
425
        #[cfg(feature = "png")]
426
        fn png_of_2x2_rgba8(fill: u8) -> Vec<u8> {
427
            use azul_core::resources::RawImageData;
428

            
429
            let img = RawImage {
430
                pixels: RawImageData::U8(vec![fill; 16].into()),
431
                width: 2,
432
                height: 2,
433
                premultiplied_alpha: false,
434
                data_format: RawImageFormat::RGBA8,
435
                tag: Vec::<u8>::new().into(),
436
            };
437
            crate::image::encode::encode_png(&img)
438
                .into_result()
439
                .expect("png encode of a well-formed 2x2 RGBA8 image failed")
440
                .as_slice()
441
                .to_vec()
442
        }
443

            
444
        #[cfg(feature = "png")]
445
        #[test]
446
        fn decode_of_every_truncation_of_a_real_png_never_panics() {
447
            let bytes = png_of_2x2_rgba8(1);
448
            assert!(bytes.len() > 33, "PNG shorter than signature + IHDR");
449

            
450
            for len in 0..bytes.len() {
451
                let r = decode_raw_image_from_any_bytes(&bytes[..len]);
452
                match r.as_result() {
453
                    // A truncation that still decodes (the trailing IEND chunk is not load
454
                    // bearing for every decoder) must at least not invent geometry or pixels.
455
                    Ok(img) => {
456
                        assert_eq!(
457
                            (img.width, img.height),
458
                            (2, 2),
459
                            "truncation to {len} bytes resized the image"
460
                        );
461
                        assert_eq!(img.pixels.get_u8_vec_ref().expect("8-bit data").len(), 16);
462
                    }
463
                    // Anything cut off before the header is complete cannot possibly decode.
464
                    Err(e) => {
465
                        assert_eq!(*e, DecodeImageError::Unknown, "truncation to {len} bytes");
466
                    }
467
                }
468
                if len <= 33 {
469
                    assert!(r.is_err(), "a {len}-byte PNG prefix decoded to an image");
470
                }
471
            }
472
        }
473

            
474
        #[cfg(feature = "png")]
475
        #[test]
476
        fn decode_of_a_corrupted_png_never_panics_or_invents_geometry() {
477
            let bytes = png_of_2x2_rgba8(9);
478

            
479
            // Flip every byte of the stream in turn: CRC/zlib checks must reject, not panic.
480
            for i in 0..bytes.len() {
481
                let mut corrupted = bytes.clone();
482
                corrupted[i] ^= 0xFF;
483
                let r = decode_raw_image_from_any_bytes(&corrupted);
484
                // Ok is acceptable in principle (e.g. a flipped byte in a padding field),
485
                // the invariant under test is "no panic, and dimensions stay sane".
486
                if let Ok(img) = r.as_result() {
487
                    assert!(
488
                        img.width <= 2 && img.height <= 2,
489
                        "corrupt byte {i} grew the image"
490
                    );
491
                }
492
            }
493
        }
494
    }
495
}
496
#[cfg(feature = "std")]
497
pub mod encode {
498
    use alloc::vec::Vec;
499
    use core::fmt;
500
    use std::io::Cursor;
501

            
502
    use azul_core::resources::{RawImage, RawImageFormat};
503
    use azul_css::{impl_result, impl_result_inner, U8Vec};
504
    #[cfg(feature = "bmp")]
505
    use image::codecs::bmp::BmpEncoder;
506
    #[cfg(feature = "gif")]
507
    use image::codecs::gif::GifEncoder;
508
    #[cfg(feature = "jpeg")]
509
    use image::codecs::jpeg::JpegEncoder;
510
    #[cfg(feature = "png")]
511
    use image::codecs::png::PngEncoder;
512
    #[cfg(feature = "pnm")]
513
    use image::codecs::pnm::PnmEncoder;
514
    #[cfg(feature = "tga")]
515
    use image::codecs::tga::TgaEncoder;
516
    #[cfg(feature = "tiff")]
517
    use image::codecs::tiff::TiffEncoder;
518
    use image::error::{ImageError, LimitError, LimitErrorKind};
519

            
520
    /// Errors that can occur when encoding a [`RawImage`] into a specific format.
521
    #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
522
    #[repr(C)]
523
    pub enum EncodeImageError {
524
        /// Crate was not compiled with the given encoder flags
525
        EncoderNotAvailable,
526
        InsufficientMemory,
527
        DimensionError,
528
        InvalidData,
529
        Unknown,
530
    }
531

            
532
    impl fmt::Display for EncodeImageError {
533
25
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534
            use self::EncodeImageError::{
535
                DimensionError, EncoderNotAvailable, InsufficientMemory, InvalidData, Unknown,
536
            };
537
25
            match self {
538
5
                EncoderNotAvailable => write!(
539
5
                    f,
540
5
                    "Missing encoder (library was not compiled with given codec)"
541
                ),
542
5
                InsufficientMemory => write!(
543
5
                    f,
544
5
                    "Error encoding image: Not enough memory available to perform encoding \
545
5
                     operation"
546
                ),
547
5
                DimensionError => write!(f, "Error encoding image: Wrong dimensions"),
548
5
                InvalidData => write!(f, "Error encoding image: Invalid data format"),
549
5
                Unknown => write!(f, "Error encoding image: Unknown error"),
550
            }
551
25
        }
552
    }
553

            
554
28
    const fn translate_rawimage_colortype(i: RawImageFormat) -> image::ColorType {
555
28
        match i {
556
2
            RawImageFormat::R8 => image::ColorType::L8,
557
2
            RawImageFormat::RG8 => image::ColorType::La8,
558
6
            RawImageFormat::RGB8 | RawImageFormat::BGR8 => image::ColorType::Rgb8,
559
6
            RawImageFormat::RGBA8 | RawImageFormat::BGRA8 => image::ColorType::Rgba8,
560
2
            RawImageFormat::R16 => image::ColorType::L16,
561
2
            RawImageFormat::RG16 => image::ColorType::La16,
562
2
            RawImageFormat::RGB16 => image::ColorType::Rgb16,
563
2
            RawImageFormat::RGBA16 => image::ColorType::Rgba16,
564
2
            RawImageFormat::RGBF32 => image::ColorType::Rgb32F,
565
2
            RawImageFormat::RGBAF32 => image::ColorType::Rgba32F,
566
        }
567
28
    }
568

            
569
293
    fn bgr_to_rgb_swap(pixels: &[u8], format: RawImageFormat) -> Option<Vec<u8>> {
570
293
        match format {
571
            RawImageFormat::BGR8 => {
572
137
                let mut out = pixels.to_vec();
573
334642
                for chunk in out.chunks_exact_mut(3) {
574
334642
                    chunk.swap(0, 2);
575
334642
                }
576
137
                Some(out)
577
            }
578
            RawImageFormat::BGRA8 => {
579
136
                let mut out = pixels.to_vec();
580
964
                for chunk in out.chunks_exact_mut(4) {
581
964
                    chunk.swap(0, 2);
582
964
                }
583
136
                Some(out)
584
            }
585
20
            _ => None,
586
        }
587
293
    }
588

            
589
    /// JPEG has no alpha channel, so alpha is dropped and BGR orders are swapped into the L8 or Rgb8 the encoder takes.
590
    #[cfg(feature = "jpeg")]
591
    fn jpeg_pixels(
592
        pixels: &[u8],
593
        format: RawImageFormat,
594
    ) -> Option<(alloc::borrow::Cow<'_, [u8]>, image::ExtendedColorType)> {
595
        use alloc::borrow::Cow;
596

            
597
        use image::ExtendedColorType::{Rgb8, L8};
598

            
599
        let rgb = |channels: usize, bgr: bool| -> Cow<'_, [u8]> {
600
            Cow::Owned(
601
                pixels
602
                    .chunks_exact(channels)
603
                    .flat_map(|px| if bgr { [px[2], px[1], px[0]] } else { [px[0], px[1], px[2]] })
604
                    .collect(),
605
            )
606
        };
607
        match format {
608
            RawImageFormat::R8 => Some((Cow::Borrowed(pixels), L8)),
609
            RawImageFormat::RG8 => Some((Cow::Owned(pixels.chunks_exact(2).map(|px| px[0]).collect()), L8)),
610
            RawImageFormat::RGB8 => Some((Cow::Borrowed(pixels), Rgb8)),
611
            RawImageFormat::BGR8 => Some((rgb(3, true), Rgb8)),
612
            RawImageFormat::RGBA8 => Some((rgb(4, false), Rgb8)),
613
            RawImageFormat::BGRA8 => Some((rgb(4, true), Rgb8)),
614
            _ => None,
615
        }
616
    }
617

            
618
8
    fn translate_image_error_encode(i: ImageError) -> EncodeImageError {
619
8
        match i {
620
3
            ImageError::Limits(l) => match l.kind() {
621
1
                LimitErrorKind::InsufficientMemory => EncodeImageError::InsufficientMemory,
622
1
                LimitErrorKind::DimensionError => EncodeImageError::DimensionError,
623
1
                _ => EncodeImageError::Unknown,
624
            },
625
5
            _ => EncodeImageError::Unknown,
626
        }
627
8
    }
628

            
629
    impl_result!(
630
        U8Vec,
631
        EncodeImageError,
632
        ResultU8VecEncodeImageError,
633
        copy = false,
634
        [Debug, Clone]
635
    );
636

            
637
    macro_rules! encode_func {
638
        ($func:ident, $encoder:ident, $feature:expr) => {
639
            #[cfg(feature = $feature)]
640
            pub fn $func(image: &RawImage) -> ResultU8VecEncodeImageError {
641
                let Ok(width) = u32::try_from(image.width) else {
642
                        return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError)
643
                    };
644
                let Ok(height) = u32::try_from(image.height) else {
645
                        return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError)
646
                    };
647
                let mut result = Vec::<u8>::new();
648

            
649
                {
650
                    let mut cursor = Cursor::new(&mut result);
651
                    let mut encoder = $encoder::new(&mut cursor);
652
                    let Some(pixels) = image.pixels.get_u8_vec_ref() else {
653
                            return ResultU8VecEncodeImageError::Err(EncodeImageError::InvalidData);
654
                        };
655

            
656
                    let swapped = bgr_to_rgb_swap(pixels.as_ref(), image.data_format);
657
                    let pixel_bytes = swapped.as_deref().unwrap_or(pixels.as_ref());
658

            
659
                    if let Err(e) = encoder.encode(
660
                        pixel_bytes,
661
                        width,
662
                        height,
663
                        translate_rawimage_colortype(image.data_format).into(),
664
                    ) {
665
                        return ResultU8VecEncodeImageError::Err(translate_image_error_encode(e));
666
                    }
667
                }
668

            
669
                ResultU8VecEncodeImageError::Ok(result.into())
670
            }
671

            
672
            #[cfg(not(feature = $feature))]
673
            #[must_use]
674
            pub const fn $func(image: &RawImage) -> ResultU8VecEncodeImageError {
675
                ResultU8VecEncodeImageError::Err(EncodeImageError::EncoderNotAvailable)
676
            }
677
        };
678
    }
679

            
680
    encode_func!(encode_bmp, BmpEncoder, "bmp");
681
    encode_func!(encode_tga, TgaEncoder, "tga");
682
    encode_func!(encode_tiff, TiffEncoder, "tiff");
683
    encode_func!(encode_gif, GifEncoder, "gif");
684
    encode_func!(encode_pnm, PnmEncoder, "pnm");
685

            
686
    #[cfg(feature = "png")]
687
    #[must_use] 
688
    pub fn encode_png(image: &RawImage) -> ResultU8VecEncodeImageError {
689
        use image::ImageEncoder;
690

            
691
        let Ok(width) = u32::try_from(image.width) else { return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError) };
692
        let Ok(height) = u32::try_from(image.height) else { return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError) };
693
        let mut result = Vec::<u8>::new();
694

            
695
        {
696
            let mut cursor = Cursor::new(&mut result);
697
            let mut encoder = PngEncoder::new_with_quality(
698
                &mut cursor,
699
                image::codecs::png::CompressionType::Best,
700
                image::codecs::png::FilterType::Adaptive,
701
            );
702
            let Some(pixels) = image.pixels.get_u8_vec_ref() else {
703
                    return ResultU8VecEncodeImageError::Err(EncodeImageError::InvalidData);
704
                };
705

            
706
            let swapped = bgr_to_rgb_swap(pixels.as_ref(), image.data_format);
707
            let pixel_bytes = swapped.as_deref().unwrap_or_else(|| pixels.as_ref());
708

            
709
            if let Err(e) = encoder.write_image(
710
                pixel_bytes,
711
                width,
712
                height,
713
                translate_rawimage_colortype(image.data_format).into(),
714
            ) {
715
                return ResultU8VecEncodeImageError::Err(translate_image_error_encode(e));
716
            }
717
        }
718

            
719
        ResultU8VecEncodeImageError::Ok(result.into())
720
    }
721

            
722
    #[cfg(not(feature = "png"))]
723
    #[must_use]
724
3
    pub const fn encode_png(image: &RawImage) -> ResultU8VecEncodeImageError {
725
3
        ResultU8VecEncodeImageError::Err(EncodeImageError::EncoderNotAvailable)
726
3
    }
727

            
728
    #[cfg(feature = "jpeg")]
729
    #[must_use] 
730
    pub fn encode_jpeg(image: &RawImage, quality: u8) -> ResultU8VecEncodeImageError {
731
        let Ok(width) = u32::try_from(image.width) else { return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError) };
732
        let Ok(height) = u32::try_from(image.height) else { return ResultU8VecEncodeImageError::Err(EncodeImageError::DimensionError) };
733
        let mut result = Vec::<u8>::new();
734

            
735
        {
736
            let mut cursor = Cursor::new(&mut result);
737
            let mut encoder = JpegEncoder::new_with_quality(&mut cursor, quality);
738
            let Some(pixels) = image.pixels.get_u8_vec_ref() else {
739
                    return ResultU8VecEncodeImageError::Err(EncodeImageError::InvalidData);
740
                };
741
            let Some((pixel_bytes, color)) = jpeg_pixels(pixels.as_ref(), image.data_format) else {
742
                return ResultU8VecEncodeImageError::Err(EncodeImageError::InvalidData);
743
            };
744

            
745
            if let Err(e) = encoder.encode(&pixel_bytes, width, height, color) {
746
                return ResultU8VecEncodeImageError::Err(translate_image_error_encode(e));
747
            }
748
        }
749

            
750
        ResultU8VecEncodeImageError::Ok(result.into())
751
    }
752

            
753
    #[cfg(not(feature = "jpeg"))]
754
    #[must_use]
755
8
    pub const fn encode_jpeg(image: &RawImage, quality: u8) -> ResultU8VecEncodeImageError {
756
8
        ResultU8VecEncodeImageError::Err(EncodeImageError::EncoderNotAvailable)
757
8
    }
758

            
759
    #[cfg(test)]
760
    mod autotest_generated {
761
        use std::collections::BTreeSet;
762

            
763
        use azul_core::resources::RawImageData;
764
        use image::error::{
765
            DecodingError, EncodingError, ImageFormatHint, ParameterError, ParameterErrorKind,
766
            UnsupportedError, UnsupportedErrorKind,
767
        };
768

            
769
        use super::*;
770

            
771
        const ALL_ERRORS: [EncodeImageError; 5] = [
772
            EncodeImageError::EncoderNotAvailable,
773
            EncodeImageError::InsufficientMemory,
774
            EncodeImageError::DimensionError,
775
            EncodeImageError::InvalidData,
776
            EncodeImageError::Unknown,
777
        ];
778

            
779
        const ALL_FORMATS: [RawImageFormat; 12] = [
780
            RawImageFormat::R8,
781
            RawImageFormat::RG8,
782
            RawImageFormat::RGB8,
783
            RawImageFormat::RGBA8,
784
            RawImageFormat::R16,
785
            RawImageFormat::RG16,
786
            RawImageFormat::RGB16,
787
            RawImageFormat::RGBA16,
788
            RawImageFormat::BGR8,
789
            RawImageFormat::BGRA8,
790
            RawImageFormat::RGBF32,
791
            RawImageFormat::RGBAF32,
792
        ];
793

            
794
        fn raw_u8(
795
            width: usize,
796
            height: usize,
797
            data_format: RawImageFormat,
798
            pixels: Vec<u8>,
799
        ) -> RawImage {
800
            RawImage {
801
                pixels: RawImageData::U8(pixels.into()),
802
                width,
803
                height,
804
                premultiplied_alpha: false,
805
                data_format,
806
                tag: Vec::<u8>::new().into(),
807
            }
808
        }
809

            
810
        #[allow(dead_code)]
811
        fn err_of(r: &ResultU8VecEncodeImageError) -> EncodeImageError {
812
            match r.as_result() {
813
                Ok(_) => panic!("expected Err, got Ok"),
814
                Err(e) => *e,
815
            }
816
        }
817

            
818
        // --- EncodeImageError::fmt (serializer) ---------------------------------
819

            
820
        #[test]
821
        fn display_every_variant_is_non_empty_and_unique() {
822
            let rendered = ALL_ERRORS.iter().map(|e| e.to_string()).collect::<Vec<_>>();
823
            for (e, s) in ALL_ERRORS.iter().zip(rendered.iter()) {
824
                assert!(!s.is_empty(), "empty Display for {e:?}");
825
            }
826
            let unique = rendered.iter().collect::<BTreeSet<_>>();
827
            assert_eq!(
828
                unique.len(),
829
                ALL_ERRORS.len(),
830
                "Display collides: {rendered:?}"
831
            );
832
        }
833

            
834
        #[test]
835
        fn display_text_is_stable() {
836
            // The odd one out: no "Error encoding image" prefix.
837
            assert_eq!(
838
                EncodeImageError::EncoderNotAvailable.to_string(),
839
                "Missing encoder (library was not compiled with given codec)"
840
            );
841
            assert_eq!(
842
                EncodeImageError::InsufficientMemory.to_string(),
843
                "Error encoding image: Not enough memory available to perform encoding operation"
844
            );
845
            assert_eq!(
846
                EncodeImageError::DimensionError.to_string(),
847
                "Error encoding image: Wrong dimensions"
848
            );
849
            assert_eq!(
850
                EncodeImageError::InvalidData.to_string(),
851
                "Error encoding image: Invalid data format"
852
            );
853
            assert_eq!(
854
                EncodeImageError::Unknown.to_string(),
855
                "Error encoding image: Unknown error"
856
            );
857
        }
858

            
859
        #[test]
860
        fn display_ignores_width_and_precision_specs_without_panicking() {
861
            for e in ALL_ERRORS {
862
                let plain = format!("{e}");
863
                assert_eq!(format!("{e:>512}"), plain);
864
                assert_eq!(format!("{e:.0}"), plain);
865
                assert!(!format!("{e:?}").is_empty());
866
            }
867
        }
868

            
869
        #[test]
870
        fn derived_ord_is_total_and_matches_declaration_order() {
871
            for (i, a) in ALL_ERRORS.iter().enumerate() {
872
                for (j, b) in ALL_ERRORS.iter().enumerate() {
873
                    assert_eq!(a.cmp(b), i.cmp(&j), "Ord disagrees for {a:?} vs {b:?}");
874
                    assert_eq!(a.partial_cmp(b), Some(a.cmp(b)));
875
                }
876
            }
877
        }
878

            
879
        // --- translate_rawimage_colortype (other) -------------------------------
880

            
881
        #[test]
882
        fn colortype_mapping_is_exhaustive_and_stable() {
883
            use image::ColorType::{
884
                La16, La8, Rgb16, Rgb32F, Rgb8, Rgba16, Rgba32F, Rgba8, L16, L8,
885
            };
886

            
887
            let expected = [
888
                (RawImageFormat::R8, L8),
889
                (RawImageFormat::RG8, La8),
890
                (RawImageFormat::RGB8, Rgb8),
891
                (RawImageFormat::RGBA8, Rgba8),
892
                (RawImageFormat::R16, L16),
893
                (RawImageFormat::RG16, La16),
894
                (RawImageFormat::RGB16, Rgb16),
895
                (RawImageFormat::RGBA16, Rgba16),
896
                (RawImageFormat::BGR8, Rgb8),
897
                (RawImageFormat::BGRA8, Rgba8),
898
                (RawImageFormat::RGBF32, Rgb32F),
899
                (RawImageFormat::RGBAF32, Rgba32F),
900
            ];
901
            assert_eq!(
902
                expected.len(),
903
                ALL_FORMATS.len(),
904
                "a RawImageFormat variant is untested"
905
            );
906
            for (format, want) in expected {
907
                assert_eq!(
908
                    translate_rawimage_colortype(format),
909
                    want,
910
                    "wrong ColorType for {format:?}"
911
                );
912
            }
913
        }
914

            
915
        #[test]
916
        fn colortype_maps_bgr_onto_its_rgb_counterpart() {
917
            // The BGR formats intentionally alias their RGB counterparts; the byte swap is
918
            // handled separately by `bgr_to_rgb_swap`.
919
            assert_eq!(
920
                translate_rawimage_colortype(RawImageFormat::BGR8),
921
                translate_rawimage_colortype(RawImageFormat::RGB8)
922
            );
923
            assert_eq!(
924
                translate_rawimage_colortype(RawImageFormat::BGRA8),
925
                translate_rawimage_colortype(RawImageFormat::RGBA8)
926
            );
927
        }
928

            
929
        #[test]
930
        fn colortype_is_usable_in_const_context() {
931
            const C: image::ColorType = translate_rawimage_colortype(RawImageFormat::RGBA16);
932
            assert_eq!(C, image::ColorType::Rgba16);
933
        }
934

            
935
        #[test]
936
        fn colortype_channel_count_matches_the_source_format() {
937
            for f in ALL_FORMATS {
938
                let channels = translate_rawimage_colortype(f).channel_count();
939
                let want = match f {
940
                    RawImageFormat::R8 | RawImageFormat::R16 => 1,
941
                    RawImageFormat::RG8 | RawImageFormat::RG16 => 2,
942
                    RawImageFormat::RGB8
943
                    | RawImageFormat::BGR8
944
                    | RawImageFormat::RGB16
945
                    | RawImageFormat::RGBF32 => 3,
946
                    RawImageFormat::RGBA8
947
                    | RawImageFormat::BGRA8
948
                    | RawImageFormat::RGBA16
949
                    | RawImageFormat::RGBAF32 => 4,
950
                };
951
                assert_eq!(channels, want, "channel count mismatch for {f:?}");
952
            }
953
        }
954

            
955
        // --- bgr_to_rgb_swap (parser) -------------------------------------------
956

            
957
        #[test]
958
        fn swap_returns_none_for_every_non_bgr_format() {
959
            for f in ALL_FORMATS {
960
                if matches!(f, RawImageFormat::BGR8 | RawImageFormat::BGRA8) {
961
                    continue;
962
                }
963
                assert_eq!(
964
                    bgr_to_rgb_swap(&[1, 2, 3, 4, 5, 6], f),
965
                    None,
966
                    "{f:?} should not swap"
967
                );
968
                assert_eq!(
969
                    bgr_to_rgb_swap(&[], f),
970
                    None,
971
                    "{f:?} should not swap (empty)"
972
                );
973
            }
974
        }
975

            
976
        #[test]
977
        fn swap_of_empty_input_is_some_empty_not_none() {
978
            // Empty input is *not* an error here: the format decides Some/None.
979
            assert_eq!(bgr_to_rgb_swap(&[], RawImageFormat::BGR8), Some(Vec::new()));
980
            assert_eq!(
981
                bgr_to_rgb_swap(&[], RawImageFormat::BGRA8),
982
                Some(Vec::new())
983
            );
984
        }
985

            
986
        #[test]
987
        fn swap_bgr8_swaps_red_and_blue_only() {
988
            assert_eq!(
989
                bgr_to_rgb_swap(&[1, 2, 3, 4, 5, 6], RawImageFormat::BGR8),
990
                Some(vec![3, 2, 1, 6, 5, 4])
991
            );
992
        }
993

            
994
        #[test]
995
        fn swap_bgra8_preserves_the_alpha_channel() {
996
            assert_eq!(
997
                bgr_to_rgb_swap(&[1, 2, 3, 200, 4, 5, 6, 201], RawImageFormat::BGRA8),
998
                Some(vec![3, 2, 1, 200, 6, 5, 4, 201])
999
            );
        }
        /// A pixel buffer whose length is not a whole number of pixels: `chunks_exact_mut`
        /// silently drops the remainder, so the trailing bytes pass through unswapped.
        #[test]
        fn swap_leaves_a_trailing_partial_pixel_untouched() {
            assert_eq!(bgr_to_rgb_swap(&[1], RawImageFormat::BGR8), Some(vec![1]));
            assert_eq!(
                bgr_to_rgb_swap(&[1, 2], RawImageFormat::BGR8),
                Some(vec![1, 2])
            );
            assert_eq!(
                bgr_to_rgb_swap(&[1, 2, 3, 4], RawImageFormat::BGR8),
                Some(vec![3, 2, 1, 4])
            );
            for len in 0..4usize {
                let input = (0..len as u8).collect::<Vec<_>>();
                assert_eq!(
                    bgr_to_rgb_swap(&input, RawImageFormat::BGRA8),
                    Some(input.clone()),
                    "a partial BGRA8 pixel of {len} byte(s) must pass through unchanged"
                );
            }
            assert_eq!(
                bgr_to_rgb_swap(&[1, 2, 3, 4, 5, 6, 7], RawImageFormat::BGRA8),
                Some(vec![3, 2, 1, 4, 5, 6, 7])
            );
        }
        #[test]
        fn swap_never_changes_the_length_and_is_its_own_inverse() {
            for (format, stride) in [(RawImageFormat::BGR8, 3usize), (RawImageFormat::BGRA8, 4)] {
                for len in 0..64usize {
                    let input = (0..len).map(|i| (i % 251) as u8).collect::<Vec<_>>();
                    let once = bgr_to_rgb_swap(&input, format).expect("BGR format must swap");
                    assert_eq!(
                        once.len(),
                        input.len(),
                        "length changed for {format:?}, len {len}"
                    );
                    let twice = bgr_to_rgb_swap(&once, format).expect("BGR format must swap");
                    assert_eq!(
                        twice, input,
                        "swap is not an involution for {format:?}, len {len}"
                    );
                    // Only whole pixels move; the tail is untouched.
                    let tail = len - (len / stride) * stride;
                    assert_eq!(once[len - tail..], input[len - tail..]);
                }
            }
        }
        #[test]
        fn swap_handles_arbitrary_non_utf8_and_unicode_bytes() {
            assert_eq!(
                bgr_to_rgb_swap(&[0xFF, 0xFE, 0x00], RawImageFormat::BGR8),
                Some(vec![0x00, 0xFE, 0xFF])
            );
            // Bytes of "\u{1F600}" (F0 9F 98 80) reinterpreted as one BGRA8 pixel.
            assert_eq!(
                bgr_to_rgb_swap("\u{1F600}".as_bytes(), RawImageFormat::BGRA8),
                Some(vec![0x98, 0x9F, 0xF0, 0x80])
            );
            assert_eq!(
                bgr_to_rgb_swap(b"   \t\n", RawImageFormat::BGR8),
                Some(vec![b' ', b' ', b' ', b'\t', b'\n'])
            );
            assert_eq!(
                bgr_to_rgb_swap(&[0, 0, 0, 255, 255, 255], RawImageFormat::BGR8),
                Some(vec![0, 0, 0, 255, 255, 255])
            );
        }
        #[test]
        fn swap_of_a_very_large_buffer_does_not_hang() {
            const LEN: usize = 3 * 333_333 + 2; // ~1 MB, deliberately not pixel-aligned
            let input = (0..LEN).map(|i| (i % 256) as u8).collect::<Vec<_>>();
            let out = bgr_to_rgb_swap(&input, RawImageFormat::BGR8).expect("BGR8 must swap");
            assert_eq!(out.len(), LEN);
            assert_eq!(out[0], input[2]);
            assert_eq!(out[2], input[0]);
            assert_eq!(out[LEN - 1], input[LEN - 1]); // partial trailing pixel kept as-is
            assert_eq!(out[LEN - 2], input[LEN - 2]);
        }
        // --- translate_image_error_encode (other) --------------------------------
        #[test]
        fn translate_maps_limit_kinds() {
            assert_eq!(
                translate_image_error_encode(ImageError::Limits(LimitError::from_kind(
                    LimitErrorKind::InsufficientMemory
                ))),
                EncodeImageError::InsufficientMemory
            );
            assert_eq!(
                translate_image_error_encode(ImageError::Limits(LimitError::from_kind(
                    LimitErrorKind::DimensionError
                ))),
                EncodeImageError::DimensionError
            );
            assert_eq!(
                translate_image_error_encode(ImageError::Limits(LimitError::from_kind(
                    LimitErrorKind::Unsupported {
                        limits: image::Limits::default(),
                        supported: image::LimitSupport::default(),
                    }
                ))),
                EncodeImageError::Unknown
            );
        }
        #[test]
        fn translate_maps_every_other_variant_to_unknown() {
            let cases = vec![
                ImageError::IoError(std::io::Error::other("boom")),
                ImageError::Encoding(EncodingError::new(ImageFormatHint::Unknown, "bad pixel")),
                ImageError::Decoding(DecodingError::new(ImageFormatHint::Unknown, "bad chunk")),
                // An unsupported *color type* (what the JPEG encoder returns for RGBA8) is
                // flattened to `Unknown`, never to `InvalidData`.
                ImageError::Unsupported(UnsupportedError::from_format_and_kind(
                    ImageFormatHint::Unknown,
                    UnsupportedErrorKind::Format(ImageFormatHint::Unknown),
                )),
                // ... and a parameter dimension mismatch is NOT mapped to DimensionError.
                ImageError::Parameter(ParameterError::from_kind(
                    ParameterErrorKind::DimensionMismatch,
                )),
            ];
            for c in cases {
                let debug = format!("{c:?}");
                assert_eq!(
                    translate_image_error_encode(c),
                    EncodeImageError::Unknown,
                    "unexpected mapping for {debug}"
                );
            }
        }
        // --- encode_png ----------------------------------------------------------
        #[cfg(feature = "png")]
        #[test]
        fn encode_png_round_trips_through_the_decoder() {
            use crate::image::decode::decode_raw_image_from_any_bytes;
            for (format, bpp) in [
                (RawImageFormat::R8, 1usize),
                (RawImageFormat::RGB8, 3),
                (RawImageFormat::RGBA8, 4),
            ] {
                let pixels = (0..(2 * 2 * bpp))
                    .map(|i| (i * 7 + 1) as u8)
                    .collect::<Vec<_>>();
                let encoded = encode_png(&raw_u8(2, 2, format, pixels.clone()))
                    .into_result()
                    .unwrap_or_else(|e| panic!("encode_png({format:?}) failed: {e}"));
                let bytes = encoded.as_slice();
                assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "missing PNG signature");
                let decoded = decode_raw_image_from_any_bytes(bytes)
                    .into_result()
                    .unwrap_or_else(|e| panic!("decode of our own PNG ({format:?}) failed: {e}"));
                assert_eq!(decoded.width, 2);
                assert_eq!(decoded.height, 2);
                assert_eq!(
                    decoded.data_format, format,
                    "format changed across the round trip"
                );
                assert!(!decoded.premultiplied_alpha);
                assert_eq!(
                    decoded
                        .pixels
                        .get_u8_vec_ref()
                        .expect("8-bit data")
                        .as_slice(),
                    pixels.as_slice(),
                    "pixels changed across the round trip ({format:?})"
                );
            }
        }
        /// BGR input must come back out of the decoder as RGB with the channels swapped
        /// (PNG has no BGR color type -- `bgr_to_rgb_swap` is what makes this correct).
        #[cfg(feature = "png")]
        #[test]
        fn encode_png_swaps_bgr_channels_before_writing() {
            use crate::image::decode::decode_raw_image_from_any_bytes;
            let bgra = vec![
                10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
            ];
            let encoded = encode_png(&raw_u8(2, 2, RawImageFormat::BGRA8, bgra.clone()))
                .into_result()
                .expect("encode_png(BGRA8) failed");
            let decoded = decode_raw_image_from_any_bytes(encoded.as_slice())
                .into_result()
                .expect("decode of our own BGRA8 PNG failed");
            assert_eq!(decoded.data_format, RawImageFormat::RGBA8);
            let want = bgr_to_rgb_swap(&bgra, RawImageFormat::BGRA8).expect("BGRA8 must swap");
            assert_eq!(
                decoded
                    .pixels
                    .get_u8_vec_ref()
                    .expect("8-bit data")
                    .as_slice(),
                want.as_slice()
            );
            let bgr = vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120];
            let encoded = encode_png(&raw_u8(2, 2, RawImageFormat::BGR8, bgr.clone()))
                .into_result()
                .expect("encode_png(BGR8) failed");
            let decoded = decode_raw_image_from_any_bytes(encoded.as_slice())
                .into_result()
                .expect("decode of our own BGR8 PNG failed");
            assert_eq!(decoded.data_format, RawImageFormat::RGB8);
            let want = bgr_to_rgb_swap(&bgr, RawImageFormat::BGR8).expect("BGR8 must swap");
            assert_eq!(
                decoded
                    .pixels
                    .get_u8_vec_ref()
                    .expect("8-bit data")
                    .as_slice(),
                want.as_slice()
            );
        }
        /// Non-8-bit payloads have no `get_u8_vec_ref()`, so they must be rejected as
        /// `InvalidData` -- even though `translate_rawimage_colortype` happily maps them.
        #[cfg(feature = "png")]
        #[test]
        fn encode_png_rejects_16_bit_and_float_payloads() {
            let u16_img = RawImage {
                pixels: RawImageData::U16(vec![0u16; 4].into()),
                width: 2,
                height: 2,
                premultiplied_alpha: false,
                data_format: RawImageFormat::R16,
                tag: Vec::<u8>::new().into(),
            };
            assert_eq!(err_of(&encode_png(&u16_img)), EncodeImageError::InvalidData);
            let f32_img = RawImage {
                pixels: RawImageData::F32(vec![0.0f32, f32::NAN, f32::INFINITY, f32::MIN].into()),
                width: 2,
                height: 2,
                premultiplied_alpha: false,
                data_format: RawImageFormat::RGBAF32,
                tag: Vec::<u8>::new().into(),
            };
            assert_eq!(err_of(&encode_png(&f32_img)), EncodeImageError::InvalidData);
        }
        #[cfg(all(feature = "png", target_pointer_width = "64"))]
        #[test]
        fn encode_png_rejects_dimensions_that_overflow_u32() {
            let too_wide = raw_u8(usize::MAX, 1, RawImageFormat::RGBA8, vec![0; 4]);
            assert_eq!(
                err_of(&encode_png(&too_wide)),
                EncodeImageError::DimensionError
            );
            let too_tall = raw_u8(
                1,
                (u32::MAX as usize) + 1,
                RawImageFormat::RGBA8,
                vec![0; 4],
            );
            assert_eq!(
                err_of(&encode_png(&too_tall)),
                EncodeImageError::DimensionError
            );
        }
        #[cfg(feature = "png")]
        #[test]
        fn encode_png_rejects_zero_dimensions() {
            let zero = raw_u8(0, 0, RawImageFormat::RGBA8, Vec::new());
            assert!(encode_png(&zero).is_err(), "a 0x0 PNG is not a valid image");
            let zero_width = raw_u8(0, 4, RawImageFormat::RGBA8, Vec::new());
            assert!(encode_png(&zero_width).is_err());
        }
        /// ADVERSARIAL: `image`'s `PngEncoder::write_image` *asserts* that the buffer length
        /// matches `width * height * bpp`, and `encode_png` forwards an unvalidated buffer.
        /// A short/long `RawImage` therefore aborts the process instead of returning `Err`.
        /// The invariant asserted here is the weaker one that always holds: it must never
        /// report success. See the report for the underlying bug.
        #[cfg(feature = "png")]
        #[test]
        fn encode_png_never_succeeds_on_a_buffer_of_the_wrong_length() {
            for (w, h, format, len) in [
                (4usize, 4usize, RawImageFormat::RGBA8, 3usize), // far too short
                (2, 2, RawImageFormat::RGBA8, 15),               // one byte short
                (2, 2, RawImageFormat::RGBA8, 17),               // one byte long
                (2, 2, RawImageFormat::R8, 0),                   // empty, non-zero dimensions
            ] {
                let outcome = std::panic::catch_unwind(move || {
                    encode_png(&raw_u8(w, h, format, vec![0u8; len])).is_ok()
                });
                assert!(
                    !matches!(outcome, Ok(true)),
                    "encode_png claimed success for {w}x{h} {format:?} with {len} byte(s)"
                );
            }
        }
        #[cfg(not(feature = "png"))]
        #[test]
        fn encode_png_without_the_feature_always_reports_encoder_not_available() {
            for img in [
                raw_u8(2, 2, RawImageFormat::RGBA8, vec![0; 16]),
                raw_u8(0, 0, RawImageFormat::RGBA8, Vec::new()),
                raw_u8(usize::MAX, usize::MAX, RawImageFormat::BGRA8, vec![0; 3]),
            ] {
                assert_eq!(
                    err_of(&encode_png(&img)),
                    EncodeImageError::EncoderNotAvailable
                );
            }
        }
        // --- encode_jpeg (numeric: `quality`) ------------------------------------
        /// `JpegEncoder::new_with_quality` clamps the quality to 1..=100 internally, so the
        /// out-of-range ends must not panic and must be indistinguishable from the clamped value.
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_clamps_quality_at_both_ends() {
            let pixels = (0..(4 * 4 * 3)).map(|i| (i * 5) as u8).collect::<Vec<_>>();
            let at = |q: u8| {
                encode_jpeg(&raw_u8(4, 4, RawImageFormat::RGB8, pixels.clone()), q)
                    .into_result()
                    .unwrap_or_else(|e| panic!("encode_jpeg(quality = {q}) failed: {e}"))
                    .as_slice()
                    .to_vec()
            };
            assert_eq!(at(u8::MIN), at(1), "quality 0 must clamp to 1");
            assert_eq!(at(u8::MAX), at(100), "quality 255 must clamp to 100");
            assert_ne!(at(1), at(100), "quality must actually affect the output");
            for q in [0u8, 1, 50, 100, 101, 254, 255] {
                let bytes = at(q);
                assert_eq!(
                    &bytes[..2],
                    &[0xFF, 0xD8],
                    "missing JPEG SOI marker (quality {q})"
                );
                assert_eq!(
                    &bytes[bytes.len() - 2..],
                    &[0xFF, 0xD9],
                    "missing JPEG EOI marker (quality {q})"
                );
            }
        }
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_round_trips_dimensions_through_the_decoder() {
            use crate::image::decode::decode_raw_image_from_any_bytes;
            let pixels = (0..(8 * 8 * 3))
                .map(|i| (i % 256) as u8)
                .collect::<Vec<_>>();
            let encoded = encode_jpeg(&raw_u8(8, 8, RawImageFormat::RGB8, pixels), 90)
                .into_result()
                .expect("encode_jpeg(RGB8) failed");
            // JPEG is lossy, so only the geometry/format survives -- not the exact pixels.
            let decoded = decode_raw_image_from_any_bytes(encoded.as_slice())
                .into_result()
                .expect("decode of our own JPEG failed");
            assert_eq!(decoded.width, 8);
            assert_eq!(decoded.height, 8);
            assert_eq!(decoded.data_format, RawImageFormat::RGB8);
            assert_eq!(
                decoded.pixels.get_u8_vec_ref().expect("8-bit data").len(),
                8 * 8 * 3
            );
        }
        /// Camera, screen and render frames are RGBA or BGRA, so JPEG drops their alpha instead of refusing them.
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_drops_alpha_and_swaps_bgr() {
            use crate::image::decode::decode_raw_image_from_any_bytes;
            let red = |format: RawImageFormat, px: &[u8]| {
                let img = raw_u8(8, 8, format, px.repeat(64));
                let jpeg = encode_jpeg(&img, 95)
                    .into_result()
                    .unwrap_or_else(|e| panic!("encode_jpeg({format:?}) failed: {e}"));
                let decoded = decode_raw_image_from_any_bytes(jpeg.as_slice())
                    .into_result()
                    .expect("decode of our own JPEG failed");
                let bytes = decoded.pixels.get_u8_vec_ref().expect("8-bit data");
                bytes.as_ref()[..3].to_vec()
            };
            for (format, px) in [
                (RawImageFormat::RGBA8, &[250u8, 10, 10, 0][..]),
                (RawImageFormat::BGRA8, &[10, 10, 250, 255][..]),
                (RawImageFormat::BGR8, &[10, 10, 250][..]),
            ] {
                let rgb = red(format, px);
                assert!(rgb[0] > 200 && rgb[1] < 60 && rgb[2] < 60, "{format:?} decoded to {rgb:?}");
            }
            assert!(encode_jpeg(&raw_u8(2, 2, RawImageFormat::RG8, vec![7; 8]), 80).is_ok());
            assert!(encode_jpeg(&raw_u8(2, 2, RawImageFormat::R8, vec![1; 4]), 80).is_ok());
            assert!(encode_jpeg(&raw_u8(2, 2, RawImageFormat::RGB8, vec![1; 12]), 80).is_ok());
            assert_eq!(
                err_of(&encode_jpeg(&raw_u8(2, 2, RawImageFormat::RGB16, vec![1; 24]), 80)),
                EncodeImageError::InvalidData
            );
        }
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_rejects_zero_and_u16_max_plus_one_dimensions() {
            // JPEG dimensions are u16 in the frame header: 0 and > 65535 must both fail,
            // and must fail as an error rather than a panic.
            assert!(encode_jpeg(&raw_u8(0, 0, RawImageFormat::RGB8, Vec::new()), 75).is_err());
            assert!(encode_jpeg(&raw_u8(0, 4, RawImageFormat::RGB8, Vec::new()), 75).is_err());
            let too_wide = raw_u8(65_536, 1, RawImageFormat::RGB8, vec![0u8; 65_536 * 3]);
            // NOTE: reported as `Unknown`, not `DimensionError` -- the wrapper only maps
            // `ImageError::Limits`, and the JPEG encoder raises an encoding error instead.
            assert_eq!(
                err_of(&encode_jpeg(&too_wide, 75)),
                EncodeImageError::Unknown
            );
        }
        #[cfg(all(feature = "jpeg", target_pointer_width = "64"))]
        #[test]
        fn encode_jpeg_rejects_dimensions_that_overflow_u32() {
            let too_wide = raw_u8(usize::MAX, 1, RawImageFormat::RGB8, vec![0; 3]);
            assert_eq!(
                err_of(&encode_jpeg(&too_wide, 75)),
                EncodeImageError::DimensionError
            );
            let too_tall = raw_u8(1, (u32::MAX as usize) + 1, RawImageFormat::RGB8, vec![0; 3]);
            assert_eq!(
                err_of(&encode_jpeg(&too_tall, 0)),
                EncodeImageError::DimensionError
            );
        }
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_rejects_16_bit_payloads_before_looking_at_quality() {
            let u16_img = RawImage {
                pixels: RawImageData::U16(vec![u16::MAX; 12].into()),
                width: 2,
                height: 2,
                premultiplied_alpha: false,
                data_format: RawImageFormat::RGB16,
                tag: Vec::<u8>::new().into(),
            };
            for q in [0u8, 50, 255] {
                assert_eq!(
                    err_of(&encode_jpeg(&u16_img, q)),
                    EncodeImageError::InvalidData
                );
            }
        }
        /// Same unvalidated-buffer hazard as `encode_png`, at every quality boundary.
        #[cfg(feature = "jpeg")]
        #[test]
        fn encode_jpeg_never_succeeds_on_a_buffer_of_the_wrong_length() {
            for q in [0u8, 1, 100, 255] {
                for (w, h, len) in [(4usize, 4usize, 3usize), (2, 2, 11), (2, 2, 13)] {
                    let outcome = std::panic::catch_unwind(move || {
                        encode_jpeg(&raw_u8(w, h, RawImageFormat::RGB8, vec![0u8; len]), q).is_ok()
                    });
                    assert!(
                        !matches!(outcome, Ok(true)),
                        "encode_jpeg claimed success for {w}x{h} RGB8, {len} byte(s), quality {q}"
                    );
                }
            }
        }
        #[cfg(not(feature = "jpeg"))]
        #[test]
        fn encode_jpeg_without_the_feature_always_reports_encoder_not_available() {
            // Every quality boundary, including the ones the real encoder would clamp.
            for q in [u8::MIN, 1, 50, 100, 101, 254, u8::MAX] {
                let img = raw_u8(2, 2, RawImageFormat::RGB8, vec![0; 12]);
                assert_eq!(
                    err_of(&encode_jpeg(&img, q)),
                    EncodeImageError::EncoderNotAvailable
                );
            }
            // ... and for images that the real encoder would reject outright.
            let broken = raw_u8(usize::MAX, 0, RawImageFormat::RGBAF32, Vec::new());
            assert_eq!(
                err_of(&encode_jpeg(&broken, 0)),
                EncodeImageError::EncoderNotAvailable
            );
        }
    }
}