utopia-image 0.1.0

Image previews: decode, crop by gravity or focal point, borders, rounded corners, opacity, rotation and background, then encode to JPEG, PNG, GIF, WebP or AVIF.
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
//! [`Image`]: a decoded image and the preview operations on it.

use std::path::Path;

use php_std::format::{ceil, dval_to_lval};
use php_std::value::Number;

use crate::color::Color;
use crate::decode;
use crate::draw;
use crate::encode;
use crate::error::{Error, Result};
use crate::frame::{self, Format, Frame};
use crate::options::{FocalPoint, Gravity, OutputFormat, canvas_bytes, check_pixels};
use crate::transform::{self, RoundRect};

/// A decoded image (every frame of an animation), transformed in place and
/// encoded on [`output`](Image::output) or [`save`](Image::save).
///
/// Every method is CPU-bound and can take tens of milliseconds on a large
/// image: in async code, run the whole pipeline on the blocking pool
/// (`utopia_async::spawn_blocking`).
///
/// Like ImageMagick, an image tracks a *current frame*: the first after
/// decoding, the last after cropping an animation. Borders, rounded corners,
/// opacity, rotation and the output format apply to the current frame only,
/// and an animation is written in its first frame's format. These are kept
/// from PHP as quirks.
///
/// PHP: `Utopia\Image\Image`.
///
/// ```
/// use utopia_image::{Gravity, Image, OutputFormat};
///
/// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
/// let mut image = Image::new(&png)?;
/// image.crop(50, 25, Gravity::Top, None)?.set_border(2, "#ff0000")?;
/// let jpeg = image.output(OutputFormat::Jpeg, 80)?;
/// assert_eq!(&jpeg[..3], &[0xFF, 0xD8, 0xFF]);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ```php
/// use Utopia\Image\Image;
///
/// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
/// $image->crop(50, 25, Image::GRAVITY_TOP)->setBorder(2, '#ff0000');
/// echo bin2hex(substr($image->output('jpg', 80), 0, 3)), "\n"; // ffd8ff
/// ```
#[derive(Debug, Clone)]
pub struct Image {
    frames: Vec<Frame>,
    current: usize,
    width: i64,
    height: i64,
    border_width: u32,
    border_color: String,
    rotation: i32,
    orientation: u32,
    wand_quality: Option<i64>,
}

/// PHP's `/` on numbers: `DivisionByZeroError` for a zero divisor.
fn div(a: f64, b: f64) -> Result<f64> {
    if b == 0.0 { Err(Error::DivisionByZero) } else { Ok(a / b) }
}

/// PHP's `intval()` of a float.
fn intval(v: f64) -> i64 {
    dval_to_lval(v)
}

impl Image {
    /// Decodes a JPEG, PNG, GIF or WebP blob, every frame of an animation, and
    /// reads its EXIF orientation (3, 6 and 8 rotate the image when it is
    /// written; mirrored orientations are ignored).
    ///
    /// The format is read from the signature first ([`Format::detect`]):
    /// anything but JPEG, PNG, GIF, WebP, AVIF and HEIC fails with
    /// [`Error::UnsupportedFormat`] before a decoder sees it.
    ///
    /// PHP: `new Image($data)`.
    pub fn new(data: &[u8]) -> Result<Image> {
        // Only decoders for the detected format ever see the data.
        let format = Format::detect(data)?;
        let frames = decode::decode(data, format)?;
        // An AVIF or HEIC decodes already rotated as the file says.
        let oriented = matches!(format, Format::Avif | Format::Heic);
        let orientation = decode::orientation(data).unwrap_or(1);
        let rotation = match orientation {
            _ if oriented => 0,
            3 => 180,
            6 => 90,
            8 => -90,
            _ => 0,
        };
        let (width, height) = (i64::from(frames[0].width()), i64::from(frames[0].height()));
        Ok(Image {
            frames,
            current: 0,
            width,
            height,
            border_width: 0,
            border_color: String::new(),
            rotation,
            orientation,
            wand_quality: None,
        })
    }

    /// A `width` x `height` image of one colour, written as PNG unless another
    /// format is asked for.
    ///
    /// PHP: `Image::create($width, $height, $background)`.
    ///
    /// ```
    /// use utopia_image::{Image, OutputFormat};
    ///
    /// let mut image = Image::blank(64, 64, "#e5e5e5")?;
    /// image.fill_path("M0 0h10v10h-10Z", "#333333", 27.0, 27.0, 1.0)?;
    /// assert_eq!(&image.output(OutputFormat::Png, 75)?[1..4], b"PNG");
    /// # Ok::<(), utopia_image::Error>(())
    /// ```
    pub fn blank(width: u32, height: u32, background: &str) -> Result<Image> {
        if width == 0 || height == 0 {
            return Err(Error::InvalidArgument("Width and height must be positive".into()));
        }
        crate::options::check_dimensions(u64::from(width), u64::from(height))?;
        let color = Color::parse(background)?;
        let pixels = image::RgbaImage::from_pixel(width, height, image::Rgba(color.0));
        Ok(Image {
            frames: vec![Frame::new(pixels, color.has_alpha(), 0, Format::Png)],
            current: 0,
            width: i64::from(width),
            height: i64::from(height),
            border_width: 0,
            border_color: String::new(),
            rotation: 0,
            orientation: 1,
            wand_quality: None,
        })
    }

    /// The EXIF orientation the image was read with (1 to 8; 1 when it had none).
    ///
    /// PHP: `getOrientation()`.
    pub fn orientation(&self) -> u32 {
        self.orientation
    }

    /// Fills SVG path data with `color` on the current frame, scaled by `scale`
    /// and then moved by `x` and `y`.
    ///
    /// PHP: `path($path, $color, $x, $y, $scale)`.
    pub fn fill_path(&mut self, path: &str, color: &str, x: f64, y: f64, scale: f64) -> Result<&mut Self> {
        draw::validate(path)?;
        let transform = zeno::Transform::scale(scale as f32, scale as f32).then_translate(x as f32, y as f32);
        draw::fill(&mut self.frames[self.current].pixels, path, transform, Color::parse(color)?);
        Ok(self)
    }

    /// Draws `text` on the current frame in `font` (TrueType or OpenType data)
    /// at `size` pixels an em, centred on `x` with its baseline at `y`.
    ///
    /// PHP: `text($text, $font, $size, $color, $x, $y)`, where `$font` is a path.
    pub fn draw_text(&mut self, text: &str, font: &[u8], size: f64, color: &str, x: f64, y: f64) -> Result<&mut Self> {
        let color = Color::parse(color)?;
        draw::text(&mut self.frames[self.current].pixels, text, font, size as f32, color, x as f32, y as f32)?;
        Ok(self)
    }

    /// The width the operations work from: the decoded width, then the last
    /// crop's (borders and rotations do not change it, as in PHP).
    pub fn width(&self) -> i64 {
        self.width
    }

    /// The height the operations work from (see [`width`](Image::width)).
    pub fn height(&self) -> i64 {
        self.height
    }

    /// Takes the current frame's size as the size later operations work from,
    /// so a step of a [`Canvas`](crate::Canvas) sees what the steps before it
    /// left (a border or a rotation changes it).
    pub(crate) fn settle(&mut self) {
        let frame = &self.frames[self.current];
        (self.width, self.height) = (i64::from(frame.width()), i64::from(frame.height()));
    }

    /// The number of frames.
    pub fn frames(&self) -> usize {
        self.frames.len()
    }

    /// Crops to `width` x `height`.
    ///
    /// Without a focal point and with [`Gravity::Center`], the image is scaled
    /// to cover the target and its centre is kept (a thumbnail crop). With
    /// another gravity or a focal point, it is scaled to cover the target and
    /// the rectangle at that gravity, or centred on the point as far as the
    /// edges allow, is kept. A zero width or height follows the aspect ratio;
    /// both zero keep the size. Every frame of an animation is cropped.
    ///
    /// PHP: `crop($width, $height, $gravity, $x, $y)`.
    ///
    /// ```
    /// use utopia_image::{FocalPoint, Gravity, Image, OutputFormat};
    ///
    /// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
    /// let mut image = Image::new(&png)?;
    /// image.crop(40, 20, Gravity::Center, Some(FocalPoint::new(0.25, 0.75)?))?;
    /// assert_eq!((image.width(), image.height()), (40, 20));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// ```php
    /// use Utopia\Image\Image;
    ///
    /// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
    /// $image->crop(40, 20, Image::GRAVITY_CENTER, x: 0.25, y: 0.75);
    /// ```
    pub fn crop(&mut self, width: u32, height: u32, gravity: Gravity, focal: Option<FocalPoint>) -> Result<&mut Self> {
        let center = gravity == Gravity::Center && focal.is_none();
        let (mut width, mut height) = (i64::from(width), i64::from(height));
        if center && width != 0 && height != 0 && width == self.width && height == self.height {
            return Ok(self);
        }
        let original_aspect = div(self.width as f64, self.height as f64)?;
        // A derived side rounds down, so a 1px side on a skewed source must not collapse to 0.
        if width == 0 && height == 0 {
            height = self.height;
            width = self.width;
        } else if width == 0 {
            width = intval(height as f64 * original_aspect).max(1);
        } else if height == 0 {
            height = intval(div(width as f64, original_aspect)?).max(1);
        }
        let (mut resize_width, mut resize_height) = (self.width, self.height);
        if !center {
            let target_aspect = div(width as f64, height as f64)?;
            if target_aspect > original_aspect {
                resize_width = width;
                resize_height = intval(ceil(Number::Float(div(width as f64, original_aspect)?)));
            } else {
                resize_width = intval(ceil(Number::Float(height as f64 * original_aspect)));
                resize_height = height;
            }
        }
        let (x, y) = crop_coordinates(width, height, resize_width, resize_height, gravity, focal);
        let dims = |v: i64| u32::try_from(v.max(0)).unwrap_or(u32::MAX);
        let (w, h, rw, rh) = (dims(width), dims(height), dims(resize_width), dims(resize_height));
        if self.frames.len() > 1 {
            // Every frame is resampled to the target and kept, and the
            // transforms below each check one canvas only: what the whole
            // animation costs is checked here, before the first allocation.
            self.check_frames(w, h, center, (resize_width, resize_height))?;
            for frame in &mut self.frames {
                if center {
                    transform::crop_thumbnail(frame, w, h)?;
                } else {
                    transform::scale(frame, rw, rh)?;
                    transform::crop(frame, w, h, x, y);
                    if w != 0 && h != 0 {
                        transform::thumbnail(frame, w, h)?;
                    }
                }
                frame.page = crate::frame::Page::at_origin(w, h);
            }
            self.current = self.frames.len() - 1;
        } else if center {
            transform::crop_thumbnail(&mut self.frames[0], w, h)?;
        } else {
            let frame = &mut self.frames[0];
            transform::scale(frame, rw, rh)?;
            transform::crop(frame, w, h, x, y);
        }
        self.width = width;
        self.height = height;
        Ok(self)
    }

    /// Adds a `width`-pixel border of `color` around the current frame
    /// (see [`Color`] for the strings accepted). The border is also what
    /// [`set_border_radius`](Image::set_border_radius) strokes.
    ///
    /// PHP: `setBorder($borderWidth, $borderColor)`. The width and colour are
    /// remembered before the colour is parsed, as in PHP.
    pub fn set_border(&mut self, width: u32, color: &str) -> Result<&mut Self> {
        self.border_width = width;
        self.border_color = color.to_owned();
        let color = Color::parse(color)?;
        transform::border(&mut self.frames[self.current], width, color)?;
        Ok(self)
    }

    /// Rounds the corners of the current frame with `radius`: outside the
    /// rounded rectangle pixels turn transparent, or black on an image without
    /// an alpha channel (a JPEG). With a border set, the rectangle is inset by
    /// it and stroked with its colour, and the image becomes that one frame.
    ///
    /// PHP: `setBorderRadius($cornerRadius)`.
    pub fn set_border_radius(&mut self, radius: u32) -> Result<&mut Self> {
        let (w, h) = (self.width, self.height);
        let bw = i64::from(self.border_width);
        let (rect_w, rect_h) = if bw > 0 { (w - (bw + 1), h - (bw + 1)) } else { (w - 1, h - 1) };
        if rect_w < bw || rect_h < bw {
            // A rectangle whose end comes before its start: ImageMagick refuses to draw it.
            return Err(Error::process("border wider than the image"));
        }
        let shape =
            RoundRect { x0: bw as f64, y0: bw as f64, x1: rect_w as f64, y1: rect_h as f64, radius: f64::from(radius) };
        let stroke = if bw > 0 { Some(Color::parse(&self.border_color)?) } else { None };
        let (mw, mh) = (u32::try_from(w.max(1)).unwrap_or(1), u32::try_from(h.max(1)).unwrap_or(1));
        transform::mask(&mut self.frames[self.current], mw, mh, &shape);
        if let Some(color) = stroke {
            let frame = transform::stroke(&self.frames[self.current], mw, mh, &shape, self.border_width, color);
            self.frames = vec![frame];
            self.current = 0;
        }
        Ok(self)
    }

    /// Sets the opacity of the current frame: every pixel's alpha becomes
    /// `opacity` of opaque (existing transparency is replaced). `1.0` changes
    /// nothing; values past `0..=1` clamp, NaN is transparent.
    ///
    /// PHP: `setOpacity($opacity)`.
    pub fn set_opacity(&mut self, opacity: f64) -> &mut Self {
        if opacity == 1.0 {
            return self;
        }
        transform::opacity(&mut self.frames[self.current], opacity);
        self
    }

    /// Rotates the current frame clockwise by `degrees`, filling with
    /// transparency; the canvas grows to fit.
    ///
    /// PHP: `setRotation($degree)`.
    pub fn set_rotation(&mut self, degrees: i64) -> Result<&mut Self> {
        if degrees == 0 {
            return Ok(self);
        }
        transform::rotate(&mut self.frames[self.current], degrees as f64)?;
        Ok(self)
    }

    /// Flattens every frame onto `color` (see [`Color`]), leaving one frame.
    ///
    /// PHP: `setBackground($color)`. The colour is set on the current frame
    /// but the flattening uses the first frame's, as in PHP.
    pub fn set_background(&mut self, color: &str) -> Result<&mut Self> {
        let color = Color::parse(color)?;
        self.frames[self.current].background = color;
        let flat = transform::flatten(&self.frames)?;
        self.frames = vec![flat];
        self.current = 0;
        Ok(self)
    }

    /// Encodes the image as `format` with `quality` (0–100; negative leaves
    /// the encoder's default), applying the pending EXIF rotation first (once).
    ///
    /// PHP: `output($type, $quality)`.
    ///
    /// ```
    /// use utopia_image::{Image, OutputFormat};
    ///
    /// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
    /// let webp = Image::new(&png)?.output("webp".parse::<OutputFormat>()?, 75)?;
    /// assert_eq!(&webp[8..12], b"WEBP");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// ```php
    /// use Utopia\Image\Image;
    ///
    /// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
    /// echo substr($image->output('webp', 75), 8, 4), "\n"; // WEBP
    /// ```
    pub fn output(&mut self, format: OutputFormat, quality: i64) -> Result<Vec<u8>> {
        self.prepare(format, quality)?;
        let first = &self.frames[0];
        encode::encode(&self.frames, first.format, first.quality, self.wand_quality)
    }

    /// Writes the image to `path`, creating its directory (mode 0755) when
    /// missing. A recognised file extension (`.png`, `.jpg`, ...) decides the
    /// format over `format`, as ImageMagick does.
    ///
    /// PHP: `save($path, $type, $quality)`.
    pub fn save(&mut self, path: impl AsRef<Path>, format: OutputFormat, quality: i64) -> Result<()> {
        let path = path.as_ref();
        let text = path.to_string_lossy();
        let dir = php_std::path::dirname(&text);
        if !Path::new(&dir).exists() && (dir.is_empty() || create_dir(&dir).is_err()) {
            return Err(Error::Failed(format!("Can't create directory {dir}")));
        }
        self.prepare(format, quality)?;
        let first = &self.frames[0];
        let written = extension_format(path).unwrap_or(first.format);
        if self.frames.len() == 1 || encode::adjoins(written) {
            let data = encode::encode(&self.frames, written, first.quality, self.wand_quality)?;
            return encode::write(path, &data);
        }
        // A format without animations gets one file per frame, numbered as
        // ImageMagick numbers them (`name-0.png`, `name-1.png`, ...); a name
        // without an extension gets only the first frame (`name-0`).
        let (quality, wand_quality) = (first.quality, self.wand_quality);
        let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
        let Some(ext) = path.extension().map(|e| e.to_string_lossy().into_owned()) else {
            let data = encode::encode(&self.frames[..1], written, quality, wand_quality)?;
            return encode::write(&path.with_file_name(format!("{stem}-0")), &data);
        };
        for (i, frame) in self.frames.iter().enumerate() {
            let data = encode::encode(std::slice::from_ref(frame), written, quality, wand_quality)?;
            encode::write(&path.with_file_name(format!("{stem}-{i}.{ext}")), &data)?;
        }
        Ok(())
    }

    /// The pending rotation, then the output settings on the current frame.
    fn prepare(&mut self, format: OutputFormat, quality: i64) -> Result<()> {
        if self.rotation != 0 {
            transform::rotate(&mut self.frames[self.current], f64::from(self.rotation))?;
            self.rotation = 0;
        }
        let frame = &mut self.frames[self.current];
        let set = quality >= 0;
        match format {
            OutputFormat::Jpeg => {
                if set {
                    frame.quality = Some(quality);
                }
                frame.format = Format::Jpeg;
            }
            OutputFormat::Gif => frame.format = Format::Gif,
            OutputFormat::Avif | OutputFormat::Heic => {
                frame.format = if format == OutputFormat::Avif { Format::Avif } else { Format::Heic };
                if set {
                    self.wand_quality = Some(if format == OutputFormat::Avif { quality.min(99) } else { quality });
                }
            }
            OutputFormat::Webp => {
                if set {
                    frame.quality = Some(quality);
                }
                frame.format = Format::Webp;
            }
            // PHP scales the quality to 0-9 and sets it on the image, which
            // ImageMagick's PNG coder never reads (see `encode::png`).
            OutputFormat::Png => {
                frame.format = Format::Png;
            }
        }
        Ok(())
    }

    /// Fails when cropping every frame to `width` x `height` would hold more
    /// pixels than the budget. A frame's new canvas replaces its old pixels,
    /// so the frames peak at whichever of the two sets is larger; on top of
    /// them the frame being worked on holds at once the canvas it is resampled
    /// to -- `resize` for a crop by gravity, the one covering the target for a
    /// centred crop -- and the canvas cropped out of it.
    fn check_frames(&self, width: u32, height: u32, center: bool, resize: (i64, i64)) -> Result<()> {
        let bytes = |(w, h): (i64, i64)| canvas_bytes(w.max(0) as u64, h.max(0) as u64);
        let target = canvas_bytes(width.into(), height.into());
        let frames = target.saturating_mul(self.frames.len() as u64);
        // A border grows the frame it was applied to and nothing else, so the
        // cover canvas is the largest frame's, not the image's.
        let cover = |frame: &Frame| bytes(transform::cover(width, height, frame.width(), frame.height()));
        let working = if center { self.frames.iter().map(cover).max().unwrap_or(0) } else { bytes(resize) };
        check_pixels(frame::retained(&self.frames).max(frames).saturating_add(working).saturating_add(target))
    }

    /// The width that keeps the aspect ratio at `height`.
    ///
    /// PHP: `getSizeByFixedHeight($newHeight)` (protected).
    pub fn size_by_fixed_height(&self, height: i64) -> Result<i64> {
        let ratio = div(self.width as f64, self.height as f64)?;
        Ok(intval(height as f64 * ratio))
    }

    /// The height that keeps the aspect ratio at `width`.
    ///
    /// PHP: `getSizeByFixedWidth($newWidth)` (protected).
    pub fn size_by_fixed_width(&self, width: i64) -> Result<i64> {
        let ratio = div(self.height as f64, self.width as f64)?;
        Ok(intval(width as f64 * ratio))
    }
}

/// `getCropCoordinates()`: the top-left corner of the crop in the scaled image.
fn crop_coordinates(
    width: i64,
    height: i64,
    resize_width: i64,
    resize_height: i64,
    gravity: Gravity,
    focal: Option<FocalPoint>,
) -> (i64, i64) {
    let (w, h, rw, rh) = (width as f64, height as f64, resize_width as f64, resize_height as f64);
    if let Some(p) = focal {
        let x = (rw - w).min(p.x() * rw - w / 2.0).max(0.0);
        let y = (rh - h).min(p.y() * rh - h / 2.0).max(0.0);
        return (intval(x), intval(y));
    }
    let mid_x = intval((rw - w) / 2.0);
    let mid_y = intval((rh - h) / 2.0);
    let (right, bottom) = (resize_width - width, resize_height - height);
    match gravity {
        Gravity::TopLeft => (0, 0),
        Gravity::Top => (mid_x, 0),
        Gravity::TopRight => (right, 0),
        Gravity::Left => (0, mid_y),
        Gravity::Right => (right, mid_y),
        Gravity::BottomLeft => (0, bottom),
        Gravity::Bottom => (mid_x, bottom),
        Gravity::BottomRight => (right, bottom),
        Gravity::Center => (mid_x, mid_y),
    }
}

/// The format ImageMagick infers from a file name's extension.
fn extension_format(path: &Path) -> Option<Format> {
    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
    Some(match ext.as_str() {
        "jpg" | "jpeg" | "jpe" => Format::Jpeg,
        "png" => Format::Png,
        "gif" => Format::Gif,
        "webp" => Format::Webp,
        "avif" => Format::Avif,
        "heic" | "heif" => Format::Heic,
        _ => return None,
    })
}

fn create_dir(dir: &str) -> std::io::Result<()> {
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o755);
    builder.create(dir)
}