Skip to main content

utopia_image/
image.rs

1//! [`Image`]: a decoded image and the preview operations on it.
2
3use std::path::Path;
4
5use php_std::format::{ceil, dval_to_lval};
6use php_std::value::Number;
7
8use crate::color::Color;
9use crate::decode;
10use crate::draw;
11use crate::encode;
12use crate::error::{Error, Result};
13use crate::frame::{self, Format, Frame};
14use crate::options::{FocalPoint, Gravity, OutputFormat, canvas_bytes, check_pixels};
15use crate::transform::{self, RoundRect};
16
17/// A decoded image (every frame of an animation), transformed in place and
18/// encoded on [`output`](Image::output) or [`save`](Image::save).
19///
20/// Every method is CPU-bound and can take tens of milliseconds on a large
21/// image: in async code, run the whole pipeline on the blocking pool
22/// (`utopia_async::spawn_blocking`).
23///
24/// Like ImageMagick, an image tracks a *current frame*: the first after
25/// decoding, the last after cropping an animation. Borders, rounded corners,
26/// opacity, rotation and the output format apply to the current frame only,
27/// and an animation is written in its first frame's format. These are kept
28/// from PHP as quirks.
29///
30/// PHP: `Utopia\Image\Image`.
31///
32/// ```
33/// use utopia_image::{Gravity, Image, OutputFormat};
34///
35/// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
36/// let mut image = Image::new(&png)?;
37/// image.crop(50, 25, Gravity::Top, None)?.set_border(2, "#ff0000")?;
38/// let jpeg = image.output(OutputFormat::Jpeg, 80)?;
39/// assert_eq!(&jpeg[..3], &[0xFF, 0xD8, 0xFF]);
40/// # Ok::<(), Box<dyn std::error::Error>>(())
41/// ```
42///
43/// ```php
44/// use Utopia\Image\Image;
45///
46/// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
47/// $image->crop(50, 25, Image::GRAVITY_TOP)->setBorder(2, '#ff0000');
48/// echo bin2hex(substr($image->output('jpg', 80), 0, 3)), "\n"; // ffd8ff
49/// ```
50#[derive(Debug, Clone)]
51pub struct Image {
52    frames: Vec<Frame>,
53    current: usize,
54    width: i64,
55    height: i64,
56    border_width: u32,
57    border_color: String,
58    rotation: i32,
59    orientation: u32,
60    wand_quality: Option<i64>,
61}
62
63/// PHP's `/` on numbers: `DivisionByZeroError` for a zero divisor.
64fn div(a: f64, b: f64) -> Result<f64> {
65    if b == 0.0 { Err(Error::DivisionByZero) } else { Ok(a / b) }
66}
67
68/// PHP's `intval()` of a float.
69fn intval(v: f64) -> i64 {
70    dval_to_lval(v)
71}
72
73impl Image {
74    /// Decodes a JPEG, PNG, GIF or WebP blob, every frame of an animation, and
75    /// reads its EXIF orientation (3, 6 and 8 rotate the image when it is
76    /// written; mirrored orientations are ignored).
77    ///
78    /// The format is read from the signature first ([`Format::detect`]):
79    /// anything but JPEG, PNG, GIF, WebP, AVIF and HEIC fails with
80    /// [`Error::UnsupportedFormat`] before a decoder sees it.
81    ///
82    /// PHP: `new Image($data)`.
83    pub fn new(data: &[u8]) -> Result<Image> {
84        // Only decoders for the detected format ever see the data.
85        let format = Format::detect(data)?;
86        let frames = decode::decode(data, format)?;
87        // An AVIF or HEIC decodes already rotated as the file says.
88        let oriented = matches!(format, Format::Avif | Format::Heic);
89        let orientation = decode::orientation(data).unwrap_or(1);
90        let rotation = match orientation {
91            _ if oriented => 0,
92            3 => 180,
93            6 => 90,
94            8 => -90,
95            _ => 0,
96        };
97        let (width, height) = (i64::from(frames[0].width()), i64::from(frames[0].height()));
98        Ok(Image {
99            frames,
100            current: 0,
101            width,
102            height,
103            border_width: 0,
104            border_color: String::new(),
105            rotation,
106            orientation,
107            wand_quality: None,
108        })
109    }
110
111    /// A `width` x `height` image of one colour, written as PNG unless another
112    /// format is asked for.
113    ///
114    /// PHP: `Image::create($width, $height, $background)`.
115    ///
116    /// ```
117    /// use utopia_image::{Image, OutputFormat};
118    ///
119    /// let mut image = Image::blank(64, 64, "#e5e5e5")?;
120    /// image.fill_path("M0 0h10v10h-10Z", "#333333", 27.0, 27.0, 1.0)?;
121    /// assert_eq!(&image.output(OutputFormat::Png, 75)?[1..4], b"PNG");
122    /// # Ok::<(), utopia_image::Error>(())
123    /// ```
124    pub fn blank(width: u32, height: u32, background: &str) -> Result<Image> {
125        if width == 0 || height == 0 {
126            return Err(Error::InvalidArgument("Width and height must be positive".into()));
127        }
128        crate::options::check_dimensions(u64::from(width), u64::from(height))?;
129        let color = Color::parse(background)?;
130        let pixels = image::RgbaImage::from_pixel(width, height, image::Rgba(color.0));
131        Ok(Image {
132            frames: vec![Frame::new(pixels, color.has_alpha(), 0, Format::Png)],
133            current: 0,
134            width: i64::from(width),
135            height: i64::from(height),
136            border_width: 0,
137            border_color: String::new(),
138            rotation: 0,
139            orientation: 1,
140            wand_quality: None,
141        })
142    }
143
144    /// The EXIF orientation the image was read with (1 to 8; 1 when it had none).
145    ///
146    /// PHP: `getOrientation()`.
147    pub fn orientation(&self) -> u32 {
148        self.orientation
149    }
150
151    /// Fills SVG path data with `color` on the current frame, scaled by `scale`
152    /// and then moved by `x` and `y`.
153    ///
154    /// PHP: `path($path, $color, $x, $y, $scale)`.
155    pub fn fill_path(&mut self, path: &str, color: &str, x: f64, y: f64, scale: f64) -> Result<&mut Self> {
156        draw::validate(path)?;
157        let transform = zeno::Transform::scale(scale as f32, scale as f32).then_translate(x as f32, y as f32);
158        draw::fill(&mut self.frames[self.current].pixels, path, transform, Color::parse(color)?);
159        Ok(self)
160    }
161
162    /// Draws `text` on the current frame in `font` (TrueType or OpenType data)
163    /// at `size` pixels an em, centred on `x` with its baseline at `y`.
164    ///
165    /// PHP: `text($text, $font, $size, $color, $x, $y)`, where `$font` is a path.
166    pub fn draw_text(&mut self, text: &str, font: &[u8], size: f64, color: &str, x: f64, y: f64) -> Result<&mut Self> {
167        let color = Color::parse(color)?;
168        draw::text(&mut self.frames[self.current].pixels, text, font, size as f32, color, x as f32, y as f32)?;
169        Ok(self)
170    }
171
172    /// The width the operations work from: the decoded width, then the last
173    /// crop's (borders and rotations do not change it, as in PHP).
174    pub fn width(&self) -> i64 {
175        self.width
176    }
177
178    /// The height the operations work from (see [`width`](Image::width)).
179    pub fn height(&self) -> i64 {
180        self.height
181    }
182
183    /// Takes the current frame's size as the size later operations work from,
184    /// so a step of a [`Canvas`](crate::Canvas) sees what the steps before it
185    /// left (a border or a rotation changes it).
186    pub(crate) fn settle(&mut self) {
187        let frame = &self.frames[self.current];
188        (self.width, self.height) = (i64::from(frame.width()), i64::from(frame.height()));
189    }
190
191    /// The number of frames.
192    pub fn frames(&self) -> usize {
193        self.frames.len()
194    }
195
196    /// Crops to `width` x `height`.
197    ///
198    /// Without a focal point and with [`Gravity::Center`], the image is scaled
199    /// to cover the target and its centre is kept (a thumbnail crop). With
200    /// another gravity or a focal point, it is scaled to cover the target and
201    /// the rectangle at that gravity, or centred on the point as far as the
202    /// edges allow, is kept. A zero width or height follows the aspect ratio;
203    /// both zero keep the size. Every frame of an animation is cropped.
204    ///
205    /// PHP: `crop($width, $height, $gravity, $x, $y)`.
206    ///
207    /// ```
208    /// use utopia_image::{FocalPoint, Gravity, Image, OutputFormat};
209    ///
210    /// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
211    /// let mut image = Image::new(&png)?;
212    /// image.crop(40, 20, Gravity::Center, Some(FocalPoint::new(0.25, 0.75)?))?;
213    /// assert_eq!((image.width(), image.height()), (40, 20));
214    /// # Ok::<(), Box<dyn std::error::Error>>(())
215    /// ```
216    ///
217    /// ```php
218    /// use Utopia\Image\Image;
219    ///
220    /// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
221    /// $image->crop(40, 20, Image::GRAVITY_CENTER, x: 0.25, y: 0.75);
222    /// ```
223    pub fn crop(&mut self, width: u32, height: u32, gravity: Gravity, focal: Option<FocalPoint>) -> Result<&mut Self> {
224        let center = gravity == Gravity::Center && focal.is_none();
225        let (mut width, mut height) = (i64::from(width), i64::from(height));
226        if center && width != 0 && height != 0 && width == self.width && height == self.height {
227            return Ok(self);
228        }
229        let original_aspect = div(self.width as f64, self.height as f64)?;
230        // A derived side rounds down, so a 1px side on a skewed source must not collapse to 0.
231        if width == 0 && height == 0 {
232            height = self.height;
233            width = self.width;
234        } else if width == 0 {
235            width = intval(height as f64 * original_aspect).max(1);
236        } else if height == 0 {
237            height = intval(div(width as f64, original_aspect)?).max(1);
238        }
239        let (mut resize_width, mut resize_height) = (self.width, self.height);
240        if !center {
241            let target_aspect = div(width as f64, height as f64)?;
242            if target_aspect > original_aspect {
243                resize_width = width;
244                resize_height = intval(ceil(Number::Float(div(width as f64, original_aspect)?)));
245            } else {
246                resize_width = intval(ceil(Number::Float(height as f64 * original_aspect)));
247                resize_height = height;
248            }
249        }
250        let (x, y) = crop_coordinates(width, height, resize_width, resize_height, gravity, focal);
251        let dims = |v: i64| u32::try_from(v.max(0)).unwrap_or(u32::MAX);
252        let (w, h, rw, rh) = (dims(width), dims(height), dims(resize_width), dims(resize_height));
253        if self.frames.len() > 1 {
254            // Every frame is resampled to the target and kept, and the
255            // transforms below each check one canvas only: what the whole
256            // animation costs is checked here, before the first allocation.
257            self.check_frames(w, h, center, (resize_width, resize_height))?;
258            for frame in &mut self.frames {
259                if center {
260                    transform::crop_thumbnail(frame, w, h)?;
261                } else {
262                    transform::scale(frame, rw, rh)?;
263                    transform::crop(frame, w, h, x, y);
264                    if w != 0 && h != 0 {
265                        transform::thumbnail(frame, w, h)?;
266                    }
267                }
268                frame.page = crate::frame::Page::at_origin(w, h);
269            }
270            self.current = self.frames.len() - 1;
271        } else if center {
272            transform::crop_thumbnail(&mut self.frames[0], w, h)?;
273        } else {
274            let frame = &mut self.frames[0];
275            transform::scale(frame, rw, rh)?;
276            transform::crop(frame, w, h, x, y);
277        }
278        self.width = width;
279        self.height = height;
280        Ok(self)
281    }
282
283    /// Adds a `width`-pixel border of `color` around the current frame
284    /// (see [`Color`] for the strings accepted). The border is also what
285    /// [`set_border_radius`](Image::set_border_radius) strokes.
286    ///
287    /// PHP: `setBorder($borderWidth, $borderColor)`. The width and colour are
288    /// remembered before the colour is parsed, as in PHP.
289    pub fn set_border(&mut self, width: u32, color: &str) -> Result<&mut Self> {
290        self.border_width = width;
291        self.border_color = color.to_owned();
292        let color = Color::parse(color)?;
293        transform::border(&mut self.frames[self.current], width, color)?;
294        Ok(self)
295    }
296
297    /// Rounds the corners of the current frame with `radius`: outside the
298    /// rounded rectangle pixels turn transparent, or black on an image without
299    /// an alpha channel (a JPEG). With a border set, the rectangle is inset by
300    /// it and stroked with its colour, and the image becomes that one frame.
301    ///
302    /// PHP: `setBorderRadius($cornerRadius)`.
303    pub fn set_border_radius(&mut self, radius: u32) -> Result<&mut Self> {
304        let (w, h) = (self.width, self.height);
305        let bw = i64::from(self.border_width);
306        let (rect_w, rect_h) = if bw > 0 { (w - (bw + 1), h - (bw + 1)) } else { (w - 1, h - 1) };
307        if rect_w < bw || rect_h < bw {
308            // A rectangle whose end comes before its start: ImageMagick refuses to draw it.
309            return Err(Error::process("border wider than the image"));
310        }
311        let shape =
312            RoundRect { x0: bw as f64, y0: bw as f64, x1: rect_w as f64, y1: rect_h as f64, radius: f64::from(radius) };
313        let stroke = if bw > 0 { Some(Color::parse(&self.border_color)?) } else { None };
314        let (mw, mh) = (u32::try_from(w.max(1)).unwrap_or(1), u32::try_from(h.max(1)).unwrap_or(1));
315        transform::mask(&mut self.frames[self.current], mw, mh, &shape);
316        if let Some(color) = stroke {
317            let frame = transform::stroke(&self.frames[self.current], mw, mh, &shape, self.border_width, color);
318            self.frames = vec![frame];
319            self.current = 0;
320        }
321        Ok(self)
322    }
323
324    /// Sets the opacity of the current frame: every pixel's alpha becomes
325    /// `opacity` of opaque (existing transparency is replaced). `1.0` changes
326    /// nothing; values past `0..=1` clamp, NaN is transparent.
327    ///
328    /// PHP: `setOpacity($opacity)`.
329    pub fn set_opacity(&mut self, opacity: f64) -> &mut Self {
330        if opacity == 1.0 {
331            return self;
332        }
333        transform::opacity(&mut self.frames[self.current], opacity);
334        self
335    }
336
337    /// Rotates the current frame clockwise by `degrees`, filling with
338    /// transparency; the canvas grows to fit.
339    ///
340    /// PHP: `setRotation($degree)`.
341    pub fn set_rotation(&mut self, degrees: i64) -> Result<&mut Self> {
342        if degrees == 0 {
343            return Ok(self);
344        }
345        transform::rotate(&mut self.frames[self.current], degrees as f64)?;
346        Ok(self)
347    }
348
349    /// Flattens every frame onto `color` (see [`Color`]), leaving one frame.
350    ///
351    /// PHP: `setBackground($color)`. The colour is set on the current frame
352    /// but the flattening uses the first frame's, as in PHP.
353    pub fn set_background(&mut self, color: &str) -> Result<&mut Self> {
354        let color = Color::parse(color)?;
355        self.frames[self.current].background = color;
356        let flat = transform::flatten(&self.frames)?;
357        self.frames = vec![flat];
358        self.current = 0;
359        Ok(self)
360    }
361
362    /// Encodes the image as `format` with `quality` (0–100; negative leaves
363    /// the encoder's default), applying the pending EXIF rotation first (once).
364    ///
365    /// PHP: `output($type, $quality)`.
366    ///
367    /// ```
368    /// use utopia_image::{Image, OutputFormat};
369    ///
370    /// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
371    /// let webp = Image::new(&png)?.output("webp".parse::<OutputFormat>()?, 75)?;
372    /// assert_eq!(&webp[8..12], b"WEBP");
373    /// # Ok::<(), Box<dyn std::error::Error>>(())
374    /// ```
375    ///
376    /// ```php
377    /// use Utopia\Image\Image;
378    ///
379    /// $image = new Image(file_get_contents('/usr/src/code/packages/image/tests/resources/resize/100x100.png'));
380    /// echo substr($image->output('webp', 75), 8, 4), "\n"; // WEBP
381    /// ```
382    pub fn output(&mut self, format: OutputFormat, quality: i64) -> Result<Vec<u8>> {
383        self.prepare(format, quality)?;
384        let first = &self.frames[0];
385        encode::encode(&self.frames, first.format, first.quality, self.wand_quality)
386    }
387
388    /// Writes the image to `path`, creating its directory (mode 0755) when
389    /// missing. A recognised file extension (`.png`, `.jpg`, ...) decides the
390    /// format over `format`, as ImageMagick does.
391    ///
392    /// PHP: `save($path, $type, $quality)`.
393    pub fn save(&mut self, path: impl AsRef<Path>, format: OutputFormat, quality: i64) -> Result<()> {
394        let path = path.as_ref();
395        let text = path.to_string_lossy();
396        let dir = php_std::path::dirname(&text);
397        if !Path::new(&dir).exists() && (dir.is_empty() || create_dir(&dir).is_err()) {
398            return Err(Error::Failed(format!("Can't create directory {dir}")));
399        }
400        self.prepare(format, quality)?;
401        let first = &self.frames[0];
402        let written = extension_format(path).unwrap_or(first.format);
403        if self.frames.len() == 1 || encode::adjoins(written) {
404            let data = encode::encode(&self.frames, written, first.quality, self.wand_quality)?;
405            return encode::write(path, &data);
406        }
407        // A format without animations gets one file per frame, numbered as
408        // ImageMagick numbers them (`name-0.png`, `name-1.png`, ...); a name
409        // without an extension gets only the first frame (`name-0`).
410        let (quality, wand_quality) = (first.quality, self.wand_quality);
411        let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
412        let Some(ext) = path.extension().map(|e| e.to_string_lossy().into_owned()) else {
413            let data = encode::encode(&self.frames[..1], written, quality, wand_quality)?;
414            return encode::write(&path.with_file_name(format!("{stem}-0")), &data);
415        };
416        for (i, frame) in self.frames.iter().enumerate() {
417            let data = encode::encode(std::slice::from_ref(frame), written, quality, wand_quality)?;
418            encode::write(&path.with_file_name(format!("{stem}-{i}.{ext}")), &data)?;
419        }
420        Ok(())
421    }
422
423    /// The pending rotation, then the output settings on the current frame.
424    fn prepare(&mut self, format: OutputFormat, quality: i64) -> Result<()> {
425        if self.rotation != 0 {
426            transform::rotate(&mut self.frames[self.current], f64::from(self.rotation))?;
427            self.rotation = 0;
428        }
429        let frame = &mut self.frames[self.current];
430        let set = quality >= 0;
431        match format {
432            OutputFormat::Jpeg => {
433                if set {
434                    frame.quality = Some(quality);
435                }
436                frame.format = Format::Jpeg;
437            }
438            OutputFormat::Gif => frame.format = Format::Gif,
439            OutputFormat::Avif | OutputFormat::Heic => {
440                frame.format = if format == OutputFormat::Avif { Format::Avif } else { Format::Heic };
441                if set {
442                    self.wand_quality = Some(if format == OutputFormat::Avif { quality.min(99) } else { quality });
443                }
444            }
445            OutputFormat::Webp => {
446                if set {
447                    frame.quality = Some(quality);
448                }
449                frame.format = Format::Webp;
450            }
451            // PHP scales the quality to 0-9 and sets it on the image, which
452            // ImageMagick's PNG coder never reads (see `encode::png`).
453            OutputFormat::Png => {
454                frame.format = Format::Png;
455            }
456        }
457        Ok(())
458    }
459
460    /// Fails when cropping every frame to `width` x `height` would hold more
461    /// pixels than the budget. A frame's new canvas replaces its old pixels,
462    /// so the frames peak at whichever of the two sets is larger; on top of
463    /// them the frame being worked on holds at once the canvas it is resampled
464    /// to -- `resize` for a crop by gravity, the one covering the target for a
465    /// centred crop -- and the canvas cropped out of it.
466    fn check_frames(&self, width: u32, height: u32, center: bool, resize: (i64, i64)) -> Result<()> {
467        let bytes = |(w, h): (i64, i64)| canvas_bytes(w.max(0) as u64, h.max(0) as u64);
468        let target = canvas_bytes(width.into(), height.into());
469        let frames = target.saturating_mul(self.frames.len() as u64);
470        // A border grows the frame it was applied to and nothing else, so the
471        // cover canvas is the largest frame's, not the image's.
472        let cover = |frame: &Frame| bytes(transform::cover(width, height, frame.width(), frame.height()));
473        let working = if center { self.frames.iter().map(cover).max().unwrap_or(0) } else { bytes(resize) };
474        check_pixels(frame::retained(&self.frames).max(frames).saturating_add(working).saturating_add(target))
475    }
476
477    /// The width that keeps the aspect ratio at `height`.
478    ///
479    /// PHP: `getSizeByFixedHeight($newHeight)` (protected).
480    pub fn size_by_fixed_height(&self, height: i64) -> Result<i64> {
481        let ratio = div(self.width as f64, self.height as f64)?;
482        Ok(intval(height as f64 * ratio))
483    }
484
485    /// The height that keeps the aspect ratio at `width`.
486    ///
487    /// PHP: `getSizeByFixedWidth($newWidth)` (protected).
488    pub fn size_by_fixed_width(&self, width: i64) -> Result<i64> {
489        let ratio = div(self.height as f64, self.width as f64)?;
490        Ok(intval(width as f64 * ratio))
491    }
492}
493
494/// `getCropCoordinates()`: the top-left corner of the crop in the scaled image.
495fn crop_coordinates(
496    width: i64,
497    height: i64,
498    resize_width: i64,
499    resize_height: i64,
500    gravity: Gravity,
501    focal: Option<FocalPoint>,
502) -> (i64, i64) {
503    let (w, h, rw, rh) = (width as f64, height as f64, resize_width as f64, resize_height as f64);
504    if let Some(p) = focal {
505        let x = (rw - w).min(p.x() * rw - w / 2.0).max(0.0);
506        let y = (rh - h).min(p.y() * rh - h / 2.0).max(0.0);
507        return (intval(x), intval(y));
508    }
509    let mid_x = intval((rw - w) / 2.0);
510    let mid_y = intval((rh - h) / 2.0);
511    let (right, bottom) = (resize_width - width, resize_height - height);
512    match gravity {
513        Gravity::TopLeft => (0, 0),
514        Gravity::Top => (mid_x, 0),
515        Gravity::TopRight => (right, 0),
516        Gravity::Left => (0, mid_y),
517        Gravity::Right => (right, mid_y),
518        Gravity::BottomLeft => (0, bottom),
519        Gravity::Bottom => (mid_x, bottom),
520        Gravity::BottomRight => (right, bottom),
521        Gravity::Center => (mid_x, mid_y),
522    }
523}
524
525/// The format ImageMagick infers from a file name's extension.
526fn extension_format(path: &Path) -> Option<Format> {
527    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
528    Some(match ext.as_str() {
529        "jpg" | "jpeg" | "jpe" => Format::Jpeg,
530        "png" => Format::Png,
531        "gif" => Format::Gif,
532        "webp" => Format::Webp,
533        "avif" => Format::Avif,
534        "heic" | "heif" => Format::Heic,
535        _ => return None,
536    })
537}
538
539fn create_dir(dir: &str) -> std::io::Result<()> {
540    let mut builder = std::fs::DirBuilder::new();
541    builder.recursive(true);
542    #[cfg(unix)]
543    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o755);
544    builder.create(dir)
545}