zune-image 0.4.1

An image library, contiaining necessary capabilities to decode, manipulate and encode images
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
/*
 * Copyright (c) 2023.
 *
 * This software is free software;
 *
 * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
 */

//! Entry point for all supported codecs the library understands
//!
//! The codecs here can be enabled and disabled at will depending on the configured interface,
//! it is recommended that you enable encoders and decoders that you only use
//!
//!
//! # Note on Compatibility with images
//!
//! - The library automatically tries to convert the image with highest compatibility
//!  this means that it will automatically convert the image to a supported bit depth
//! and supported colorspace in case the image is not in the supported colorspace
//!   E.g if you open a HDR or EXR image whose format is `f32` `[0.0-1.0]` and convert it to JPEG,
//! which understands 8 bit images`[0-255]`, the library will internally convert it to 8 bit images
//!
//! - For image depth, we convert it to the most appropriate depth, e.g trying to store F32 images in png
//! will convert it to 16 bit images, this allows us to preserve as much information as possible
//! during the conversation.
//!
//! - **Warning**: For this to work, the image will be cloned and the depth or colorspace modified on the
//!  clone. The current image is left as is, unmodified.
//!  **This may cause huge memory usage as cloning is expensive**
//!
//!
#![allow(unused_imports, unused_variables, non_camel_case_types)]

use std::io::Cursor;
use std::path::Path;

use zune_core::bytestream::{ZByteReader, ZReaderTrait};
use zune_core::log::trace;
use zune_core::options::{DecoderOptions, EncoderOptions};

use crate::codecs;
use crate::codecs::ImageFormat::JPEG_XL;
use crate::errors::ImgEncodeErrors::ImageEncodeErrors;
use crate::errors::{ImageErrors, ImgEncodeErrors};
use crate::image::Image;
use crate::traits::{DecoderTrait, EncoderTrait};

pub mod bmp;
mod exr;
pub mod farbfeld;
pub mod hdr;
pub mod jpeg;
pub mod jpeg_xl;
pub mod png;
pub mod ppm;
pub mod psd;
pub mod qoi;
pub(crate) fn create_options_for_encoder(
    options: Option<EncoderOptions>, image: &Image
) -> EncoderOptions {
    // choose if we take options from pre-configured , or we create default options
    let start_options = if let Some(configured_opts) = options {
        configured_opts
    } else {
        EncoderOptions::default()
    };
    let (width, height) = image.dimensions();
    // then set image configuration
    start_options
        .set_width(width)
        .set_height(height)
        .set_depth(image.depth())
        .set_colorspace(image.colorspace())
}
/// All supported image formats
///
/// This enum contains supported image formats, either
/// encoders or decoders for a particular image
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ImageFormat {
    /// Joint Photographic Experts Group
    JPEG,
    /// Portable Network Graphics
    PNG,
    /// Portable Pixel Map image
    PPM,
    /// Photoshop PSD component
    PSD,
    /// Farbfeld format
    Farbfeld,
    /// Quite Okay Image
    QOI,
    /// JPEG XL, new format
    JPEG_XL,
    /// Radiance HDR decoder
    HDR,
    /// Windows Bitmap Files
    BMP,
    /// Any unknown format
    Unknown
}

impl ImageFormat {
    /// Return true if an image format has an encoder that can convert the image
    /// into that format
    pub fn has_encoder(self) -> bool {
        self.get_encoder().is_some()
    }

    pub fn has_decoder(self) -> bool {
        #[cfg(feature = "jpeg-xl")]
        {
            // for jpeg-xl we  know we have a decoder when the header can be parsed
            // but here, we aren't passing any data below, and since we are using is_ok()
            // to determine if we have okay, the jxl one will always fail.
            //
            // So we lift the check out of the decoder and do it here
            if self == JPEG_XL {
                return true;
            }
        }
        return self.get_decoder::<&[u8]>(&[]).is_ok();
    }
    pub fn get_decoder<'a, T>(&self, data: T) -> Result<Box<dyn DecoderTrait<T> + 'a>, ImageErrors>
    where
        T: ZReaderTrait + 'a
    {
        self.get_decoder_with_options(data, DecoderOptions::default())
    }

    pub fn get_decoder_with_options<'a, T>(
        &self, data: T, options: DecoderOptions
    ) -> Result<Box<dyn DecoderTrait<T> + 'a>, ImageErrors>
    where
        T: ZReaderTrait + 'a
    {
        match self {
            ImageFormat::JPEG => {
                #[cfg(feature = "jpeg")]
                {
                    Ok(Box::new(zune_jpeg::JpegDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "jpeg"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }

            ImageFormat::PNG => {
                #[cfg(feature = "png")]
                {
                    Ok(Box::new(zune_png::PngDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "png"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::PPM => {
                #[cfg(feature = "ppm")]
                {
                    Ok(Box::new(zune_ppm::PPMDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "ppm"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::PSD => {
                #[cfg(feature = "ppm")]
                {
                    Ok(Box::new(zune_psd::PSDDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "ppm"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }

            ImageFormat::Farbfeld => {
                #[cfg(feature = "farbfeld")]
                {
                    Ok(Box::new(zune_farbfeld::FarbFeldDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "farbfeld"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }

            ImageFormat::QOI => {
                #[cfg(feature = "qoi")]
                {
                    Ok(Box::new(zune_qoi::QoiDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "qoi"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::HDR => {
                #[cfg(feature = "hdr")]
                {
                    Ok(Box::new(zune_hdr::HdrDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "hdr"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::BMP => {
                #[cfg(feature = "bmp")]
                {
                    Ok(Box::new(zune_bmp::BmpDecoder::new_with_options(
                        data, options
                    )))
                }
                #[cfg(not(feature = "bmp"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::JPEG_XL => {
                #[cfg(feature = "jpeg-xl")]
                {
                    // use a ZByteReader which implements read, this prevents unnecessary
                    // copy
                    let reader = ZByteReader::new(data);

                    Ok(Box::new(codecs::jpeg_xl::JxlDecoder::try_new(
                        reader, options
                    )?))
                }
                #[cfg(not(feature = "jpeg-xl"))]
                {
                    Err(ImageErrors::ImageDecoderNotIncluded(*self))
                }
            }
            ImageFormat::Unknown => Err(ImageErrors::ImageDecoderNotImplemented(*self))
        }
    }

    pub fn get_encoder(&self) -> Option<Box<dyn EncoderTrait>> {
        self.get_encoder_with_options(EncoderOptions::default())
    }
    pub fn get_encoder_with_options(
        &self, options: EncoderOptions
    ) -> Option<Box<dyn EncoderTrait>> {
        match self {
            Self::PPM => {
                #[cfg(feature = "ppm")]
                {
                    Some(Box::new(crate::codecs::ppm::PPMEncoder::new_with_options(
                        options
                    )))
                }
                #[cfg(not(feature = "ppm"))]
                {
                    None
                }
            }
            Self::QOI => {
                #[cfg(feature = "qoi")]
                {
                    Some(Box::new(crate::codecs::qoi::QoiEncoder::new_with_options(
                        options
                    )))
                }
                #[cfg(not(feature = "qoi"))]
                {
                    None
                }
            }
            Self::JPEG => {
                #[cfg(feature = "jpeg")]
                {
                    Some(Box::new(
                        crate::codecs::jpeg::JpegEncoder::new_with_options(options)
                    ))
                }
                #[cfg(not(feature = "jpeg"))]
                {
                    None
                }
            }
            Self::JPEG_XL => {
                #[cfg(feature = "jpeg-xl")]
                {
                    Some(Box::new(
                        crate::codecs::jpeg_xl::JxlEncoder::new_with_options(options)
                    ))
                }
                #[cfg(not(feature = "jpeg-xl"))]
                {
                    None
                }
            }
            Self::HDR => {
                #[cfg(feature = "hdr")]
                {
                    Some(Box::new(crate::codecs::hdr::HdrEncoder::new_with_options(
                        options
                    )))
                }
                #[cfg(not(feature = "hdr"))]
                {
                    None
                }
            }
            Self::PNG => {
                #[cfg(feature = "png")]
                {
                    Some(Box::new(codecs::png::PngEncoder::new_with_options(options)))
                }
                #[cfg(not(feature = "png"))]
                {
                    None
                }
            }
            // all encoders not implemented default to none
            _ => None
        }
    }
    pub fn guess_format<T>(bytes: T) -> Option<(ImageFormat, T)>
    where
        T: ZReaderTrait
    {
        guess_format(bytes)
    }

    pub fn get_encoder_for_extension<P: AsRef<str>>(
        extension: P
    ) -> Option<(ImageFormat, Box<dyn EncoderTrait>)> {
        match extension.as_ref() {
            "qoi" => {
                #[cfg(feature = "qoi")]
                {
                    Some((ImageFormat::QOI, ImageFormat::QOI.get_encoder().unwrap()))
                }
                #[cfg(not(feature = "qoi"))]
                {
                    None
                }
            }
            "ppm" | "pam" | "pgm" | "pbm" | "pfm" => {
                #[cfg(feature = "ppm")]
                {
                    Some((ImageFormat::PPM, ImageFormat::PPM.get_encoder().unwrap()))
                }
                #[cfg(not(feature = "ppm"))]
                {
                    None
                }
            }
            "jpeg" | "jpg" => {
                #[cfg(feature = "jpeg")]
                {
                    Some((ImageFormat::JPEG, ImageFormat::JPEG.get_encoder().unwrap()))
                }
                #[cfg(not(feature = "jpeg"))]
                {
                    None
                }
            }
            "jxl" => {
                #[cfg(feature = "jpeg-xl")]
                {
                    Some((
                        ImageFormat::JPEG_XL,
                        ImageFormat::JPEG_XL.get_encoder().unwrap()
                    ))
                }
                #[cfg(not(feature = "jpeg-xl"))]
                {
                    None
                }
            }
            "ff" => {
                #[cfg(feature = "farbfeld")]
                {
                    Some((
                        ImageFormat::Farbfeld,
                        ImageFormat::Farbfeld.get_encoder().unwrap()
                    ))
                }
                #[cfg(not(feature = "farbfeld"))]
                {
                    None
                }
            }
            "hdr" => {
                #[cfg(feature = "hdr")]
                {
                    Some((ImageFormat::HDR, ImageFormat::HDR.get_encoder().unwrap()))
                }
                #[cfg(not(feature = "hdr"))]
                {
                    None
                }
            }
            "png" => {
                #[cfg(feature = "png")]
                {
                    Some((ImageFormat::PNG, ImageFormat::PNG.get_encoder().unwrap()))
                }
                #[cfg(not(feature = "png"))]
                {
                    None
                }
            }
            _ => None
        }
    }
}

// save options
impl Image {
    /// Save the image to a file and use the extension to
    /// determine the format
    ///
    /// If the extension cannot be determined from the path, it's an error.
    ///
    /// # Arguments
    ///
    /// * `file`: The file to save the image to
    ///
    /// returns: Result<(), ImageErrors>
    ///
    /// # Examples
    ///
    ///  - Encode image to jpeg format, requires `jpeg` feature
    ///
    /// ```
    /// use zune_core::colorspace::ColorSpace;
    /// use zune_image::image::Image;
    /// // create a luma image
    /// let image = Image::fill::<u8>(128,ColorSpace::Luma,100,100).unwrap();
    /// // save to jpeg
    /// image.save("hello.jpg").unwrap();
    /// ```
    pub fn save<P: AsRef<Path>>(&self, file: P) -> Result<(), ImageErrors> {
        return if let Some(ext) = file.as_ref().extension() {
            if let Some((format, _)) = ImageFormat::get_encoder_for_extension(ext.to_str().unwrap())
            {
                self.save_to(file, format)
            } else {
                let msg = format!("No encoder for extension {ext:?}");

                Err(ImageErrors::EncodeErrors(ImgEncodeErrors::Generic(msg)))
            }
        } else {
            let msg = format!("No extension for file {:?}", file.as_ref());

            Err(ImageErrors::EncodeErrors(ImgEncodeErrors::Generic(msg)))
        };
    }
    /// Save an image using a specified format to a file
    ///
    /// The image may be cloned and the clone modified to fit preferences
    /// for that specific image format, e.g if the image is in f32 and being saved
    /// to jpeg, the clone will be modified to be in u8, and that will be the format
    /// saved to jpeg.
    ///
    /// # Arguments
    ///
    /// * `file`: The file path to which the image will be saved
    /// * `format`: The format to save the image into. It's an error if the
    ///     format doesn't have an encoder(not all formats do)
    ///
    /// returns: Result<(), ImageErrors>
    ///
    ///
    /// # Examples
    ///
    ///  - Save a black grayscale image to JPEG, requires the JPEG feature
    /// ```no_run
    /// use zune_core::colorspace::ColorSpace;
    /// use zune_image::codecs::ImageFormat;
    /// use zune_image::image::Image;
    /// // create a simple 200x200 grayscale image consisting of pure black
    /// let image = Image::fill::<u8>(0,ColorSpace::Luma,200,200).unwrap();
    /// // save that to jpeg
    /// image.save_to("black.jpg",ImageFormat::JPEG).unwrap();
    /// ```
    pub fn save_to<P: AsRef<Path>>(&self, file: P, format: ImageFormat) -> Result<(), ImageErrors> {
        let contents = self.write_to_vec(format)?;
        std::fs::write(file, contents)?;
        Ok(())
    }

    /// Encode an image returning a vector containing the result
    /// of the encoding
    ///
    /// # Arguments
    ///
    /// * `format`: The format to use for encoding, it's an error if the
    /// relevant encoder is not present either because it's not supported, or it's not
    /// included as a feature.
    ///
    /// returns: `Result<Vec<u8, Global>, ImageErrors>`
    ///
    /// # Examples
    ///
    /// - Encode a simple image to QOI format, needs qoi format to be enabled
    /// ```
    /// use zune_core::colorspace::ColorSpace;
    /// use zune_image::codecs::ImageFormat;
    /// use zune_image::image::Image;
    /// // create an image using from fn, to generate a gradient image
    /// let image = Image::from_fn::<u8,_>(300,300,ColorSpace::RGB,|x,y,px|{
    ///         let r = (0.3 * x as f32) as u8;
    ///         let b = (0.3 * y as f32) as u8;
    ///         px[0] = r;
    ///         px[2] = b;
    /// });
    /// // write to qoi now
    /// let contents = image.write_to_vec(ImageFormat::QOI).unwrap();
    /// ```
    pub fn write_to_vec(&self, format: ImageFormat) -> Result<Vec<u8>, ImageErrors> {
        if let Some(mut encoder) = format.get_encoder() {
            // encode
            encoder.encode(self)
        } else {
            Err(ImageErrors::EncodeErrors(
                crate::errors::ImgEncodeErrors::NoEncoderForFormat(format)
            ))
        }
    }

    /// Open an encoded file for which the library has a configured decoder for it
    ///
    /// # Note
    /// - This reads the whole file into memory before parsing
    /// do not use for large files
    ///
    /// - The decoders supported can be switched on and off depending on how
    ///  you configure your Cargo.toml. It is generally recommended to not enable decoders
    ///  you will not be using as it reduces both the security attack surface and dependency
    ///
    /// # Arguments
    /// - file: The file path from which to read the file from, the file must be a supported format
    /// otherwise it's an error to try and decode
    ///
    /// See also [open_from_mem](Self::read) for reading from memory
    pub fn open<P: AsRef<Path>>(file: P) -> Result<Image, ImageErrors> {
        Self::open_with_options(file, DecoderOptions::default())
    }

    /// Open an encoded file for which the library has a configured decoder for it
    /// with the specified custom decoder options
    ///
    /// This allows you to modify decoding steps  where possible by specifying how the
    /// decoder should behave
    ///
    /// # Example
    ///  -  Decode a file with strict mode enabled and only expect images with less
    ///  than 100 pixels in width
    ///
    /// ```no_run
    /// use zune_core::options::DecoderOptions;
    /// use zune_image::image::Image;
    /// let options = DecoderOptions::default().set_strict_mode(true).set_max_width(100);
    /// let image = Image::open_with_options("/a/file.jpeg",options).unwrap();
    /// ```
    pub fn open_with_options<P: AsRef<Path>>(
        file: P, options: DecoderOptions
    ) -> Result<Image, ImageErrors> {
        let file = std::fs::read(file)?;

        Self::read(file, options)
    }
    /// Open a new file from memory with the configured options
    ///  
    /// # Arguments
    ///  - `src`: The encoded buffer loaded into memory
    ///  - `options`: The configured decoded options
    /// # Example
    /// - Open a memory source with the default options
    ///
    ///```no_run
    /// use zune_core::options::DecoderOptions;
    /// use zune_image::image::Image;
    /// // create a simple ppm p5 grayscale format
    /// let image = Image::read(b"P5 1 1 255 1",DecoderOptions::default());
    ///```
    pub fn read<T>(src: T, options: DecoderOptions) -> Result<Image, ImageErrors>
    where
        T: ZReaderTrait
    {
        let decoder = ImageFormat::guess_format(src);

        if let Some(format) = decoder {
            let mut image_decoder = format.0.get_decoder_with_options(format.1, options)?;
            // save format
            let mut image = image_decoder.decode()?;
            image.metadata.format = Some(format.0);
            Ok(image)
        } else {
            Err(ImageErrors::ImageDecoderNotImplemented(
                ImageFormat::Unknown
            ))
        }
    }
}
/// Guess the format of an image based on it's magic bytes
///
/// # Arguments
/// - bytes: The data source containing the image pixels
///
/// # Returns
/// - Some(format,T): The image format and the data source.
/// - None: Indicates the format isn't known/understood by the library
pub fn guess_format<T>(bytes: T) -> Option<(ImageFormat, T)>
where
    T: ZReaderTrait
{
    let reader = ZByteReader::new(bytes);
    // stolen from imagers
    let magic_bytes: Vec<(&[u8], ImageFormat)> = vec![
        (&[137, 80, 78, 71, 13, 10, 26, 10], ImageFormat::PNG),
        // Of course with jpg we need to relax our definition of what is a jpeg
        // the best identifier would be 0xFF,0xd8 0xff but nop, some images exist
        // which do not have that
        (&[0xff, 0xd8], ImageFormat::JPEG),
        (b"P5", ImageFormat::PPM),
        (b"P6", ImageFormat::PPM),
        (b"P7", ImageFormat::PPM),
        (b"Pf", ImageFormat::PPM),
        (b"PF", ImageFormat::PPM),
        (b"8BPS", ImageFormat::PSD),
        (b"farbfeld", ImageFormat::Farbfeld),
        (b"qoif", ImageFormat::QOI),
        (b"#?RADIANCE\n", ImageFormat::HDR),
        (b"#?RGBE\n", ImageFormat::HDR),
        (
            &[
                0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x4C, 0x20, 0x0D, 0x0A, 0x87, 0x0A
            ],
            ImageFormat::JPEG_XL
        ),
        (&[0xFF, 0x0A], ImageFormat::JPEG_XL),
    ];

    for (magic, decoder) in magic_bytes {
        if (reader.has(magic.len())) && reader.peek_at(0, magic.len()).unwrap().starts_with(magic) {
            return Some((decoder, reader.consume()));
        }
    }
    #[cfg(feature = "bmp")]
    {
        // get a slice reference
        // bmp requires 15 bytes to determine if it is a valid one.
        // so take 16 just to be safe
        if reader.has(16) {
            let reference = reader.peek_at(0, 16).unwrap();

            if zune_bmp::probe_bmp(reference) {
                return Some((ImageFormat::BMP, reader.consume()));
            }
        }
    }

    None
}