Skip to main content

utopia_image/
canvas.rs

1//! [`Canvas`]: an image and the work planned on it, done when it is encoded.
2
3use std::io::Cursor;
4use std::sync::Arc;
5
6use crate::color::Color;
7use crate::decode;
8use crate::error::{Error, Result};
9use crate::format::Format;
10use crate::image::Image;
11use crate::options::{FocalPoint, Gravity, Limits, OutputFormat, check_dimensions};
12
13/// One preview: a crop, then opacity, a background, a border, rounded corners
14/// and a rotation, in that order. A part left at its default is skipped.
15///
16/// PHP: `Utopia\Image\Transform`.
17#[derive(Debug, Clone, PartialEq)]
18pub struct Transform {
19    /// The width to crop to; 0 follows the aspect ratio.
20    pub width: u32,
21    /// The height to crop to; 0 follows the aspect ratio.
22    pub height: u32,
23    /// Which part of the image a crop keeps.
24    pub gravity: Gravity,
25    /// A point to keep in view, which overrides `gravity`.
26    pub focus: Option<FocalPoint>,
27    /// From 0 (transparent) to 1 (unchanged).
28    pub opacity: f64,
29    /// A colour to flatten the image onto.
30    pub background: Option<String>,
31    /// A border's width in pixels and its colour.
32    pub border: Option<(u32, String)>,
33    /// The corner radius in pixels.
34    pub radius: u32,
35    /// Degrees clockwise.
36    pub rotation: i64,
37}
38
39impl Default for Transform {
40    fn default() -> Self {
41        Transform {
42            width: 0,
43            height: 0,
44            gravity: Gravity::Center,
45            focus: None,
46            opacity: 1.0,
47            background: None,
48            border: None,
49            radius: 0,
50            rotation: 0,
51        }
52    }
53}
54
55/// Something drawn onto a canvas.
56#[derive(Debug, Clone)]
57pub enum Drawing {
58    /// SVG path data filled with a colour, scaled and then moved.
59    Path {
60        /// The path data, as in an SVG `d` attribute.
61        data: String,
62        /// The fill colour.
63        color: String,
64        /// How far right to move the scaled path.
65        x: f64,
66        /// How far down to move the scaled path.
67        y: f64,
68        /// The factor the path's own units are multiplied by.
69        scale: f64,
70    },
71    /// A line of text, without kerning or shaping.
72    Text {
73        /// The characters to draw; one the font has no glyph for takes no space.
74        text: String,
75        /// TrueType or OpenType font data.
76        font: Arc<[u8]>,
77        /// Pixels an em.
78        size: f64,
79        /// The fill colour.
80        color: String,
81        /// The horizontal centre of the line.
82        x: f64,
83        /// The baseline.
84        y: f64,
85    },
86}
87
88#[derive(Debug, Clone)]
89enum Source {
90    Encoded(Arc<[u8]>),
91    Blank { background: String },
92}
93
94#[derive(Debug, Clone)]
95enum Step {
96    Transform(Transform),
97    Drawing(Drawing),
98}
99
100/// An image, and what has been asked of it so far.
101///
102/// A canvas is immutable: [`apply`](Canvas::apply) and [`draw`](Canvas::draw)
103/// return a new one that shares the source bytes. Steps run in the order they
104/// were added, each on what the one before it left. Nothing is decoded until
105/// [`encode`](Canvas::encode), which decodes, runs every step and writes the
106/// result in one pass. The size, format and orientation come from the header.
107///
108/// PHP: `Utopia\Image\Canvas`.
109///
110/// ```
111/// use utopia_image::{Canvas, Limits, OutputFormat, Transform};
112///
113/// let png = std::fs::read("../../../packages/image/tests/resources/resize/100x100.png")?;
114/// let canvas = Canvas::decode(&png, Limits::default())?;
115/// assert_eq!((canvas.width(), canvas.height()), (100, 100));
116/// let jpeg = canvas.apply(Transform { width: 50, height: 25, ..Transform::default() })?.encode(OutputFormat::Jpeg, Some(80))?;
117/// assert_eq!(&jpeg[..3], &[0xFF, 0xD8, 0xFF]);
118/// # Ok::<(), Box<dyn std::error::Error>>(())
119/// ```
120#[derive(Debug, Clone)]
121pub struct Canvas {
122    source: Source,
123    limits: Limits,
124    steps: Vec<Step>,
125    width: u32,
126    height: u32,
127    orientation: u32,
128    format: Option<Format>,
129}
130
131/// The size a file's header declares, without decoding its pixels.
132fn dimensions(data: &[u8], format: Format) -> Result<(u32, u32)> {
133    let corrupt = |e: image::ImageError| Error::Corrupt(format!("{}: {e}", format.value()));
134    let kind = match format {
135        Format::Jpeg => image::ImageFormat::Jpeg,
136        Format::Png => image::ImageFormat::Png,
137        Format::Gif => image::ImageFormat::Gif,
138        Format::Webp => image::ImageFormat::WebP,
139        #[cfg(feature = "libheif")]
140        Format::Avif | Format::Heic => return crate::heif::dimensions(data, format),
141        #[cfg(not(feature = "libheif"))]
142        Format::Avif | Format::Heic => return Err(Error::unavailable(format.value(), "input")),
143    };
144    image::ImageReader::with_format(Cursor::new(data), kind).into_dimensions().map_err(corrupt)
145}
146
147impl Canvas {
148    /// Reads the header of a JPEG, PNG, GIF, WebP, AVIF or HEIC file.
149    ///
150    /// Fails here, before any pixel is decoded, for a format that is not one of
151    /// `accept`, a header that cannot be read, or a size past `limits`. A file
152    /// whose pixel data is damaged fails later, in [`encode`](Canvas::encode).
153    ///
154    /// PHP: `new Canvas($data, $limits)`.
155    pub fn decode(data: &[u8], limits: Limits) -> Result<Canvas> {
156        Canvas::decode_accepting(data, limits, &[])
157    }
158
159    /// As [`decode`](Canvas::decode), refusing any format not in `accept` (every format when empty).
160    pub fn decode_accepting(data: &[u8], limits: Limits, accept: &[Format]) -> Result<Canvas> {
161        let format = Format::detect(data)?;
162        if !accept.is_empty() && !accept.contains(&format) {
163            return Err(Error::UnsupportedFormat(format!("{} input is not accepted", format.value())));
164        }
165        let (width, height) = dimensions(data, format)?;
166        limits.scope(|| check_dimensions(width.into(), height.into()))?;
167        Ok(Canvas {
168            source: Source::Encoded(data.into()),
169            limits,
170            steps: Vec::new(),
171            width,
172            height,
173            orientation: decode::orientation(data).unwrap_or(1),
174            format: Some(format),
175        })
176    }
177
178    /// A canvas of one colour.
179    ///
180    /// PHP: `new Canvas(new Blank($width, $height, $background), $limits)`.
181    pub fn blank(width: u32, height: u32, background: &str, limits: Limits) -> Result<Canvas> {
182        // Builds and drops a one-pixel image to reject a bad size or colour now.
183        limits.scope(|| {
184            check_dimensions(width.into(), height.into())?;
185            Image::blank(width.min(1), height.min(1), background).map(|_| ())
186        })?;
187        Ok(Canvas {
188            source: Source::Blank { background: background.to_owned() },
189            limits,
190            steps: Vec::new(),
191            width,
192            height,
193            orientation: 1,
194            format: None,
195        })
196    }
197
198    /// The width of the source, before any step.
199    pub fn width(&self) -> u32 {
200        self.width
201    }
202
203    /// The height of the source, before any step.
204    pub fn height(&self) -> u32 {
205        self.height
206    }
207
208    /// The EXIF orientation of the source, 1 to 8 (1 when it has none).
209    pub fn orientation(&self) -> u32 {
210        self.orientation
211    }
212
213    /// The format of the source; `None` for a blank canvas.
214    pub fn format(&self) -> Option<Format> {
215        self.format
216    }
217
218    /// A canvas with `transform` added to its plan. Fails for a colour that cannot be parsed,
219    /// or a size past the canvas's limits.
220    pub fn apply(&self, transform: Transform) -> Result<Canvas> {
221        if u64::from(transform.width) > self.limits.width || u64::from(transform.height) > self.limits.height {
222            return Err(Error::LimitExceeded);
223        }
224        let colors = [transform.background.as_deref(), transform.border.as_ref().map(|(_, color)| color.as_str())];
225        for color in colors.into_iter().flatten() {
226            Color::parse(color)?;
227        }
228        let mut canvas = self.clone();
229        canvas.steps.push(Step::Transform(transform));
230        Ok(canvas)
231    }
232
233    /// A canvas with `drawing` added to its plan. Fails for a colour, a path or a font that
234    /// cannot be parsed.
235    pub fn draw(&self, drawing: Drawing) -> Result<Canvas> {
236        match &drawing {
237            Drawing::Path { data, color, .. } => {
238                crate::draw::validate(data)?;
239                Color::parse(color)?;
240            }
241            Drawing::Text { font, color, .. } => {
242                crate::draw::has_glyph(font, ' ')?;
243                Color::parse(color)?;
244            }
245        }
246        let mut canvas = self.clone();
247        canvas.steps.push(Step::Drawing(drawing));
248        Ok(canvas)
249    }
250
251    /// Decodes the source, runs the plan and writes `format`.
252    ///
253    /// `quality` is 0 to 100; `None` keeps a JPEG source's own quality and
254    /// otherwise uses the format's default. Metadata is not written.
255    pub fn encode(&self, format: OutputFormat, quality: Option<u8>) -> Result<Vec<u8>> {
256        self.limits.scope(|| {
257            let mut image = match &self.source {
258                Source::Encoded(data) => Image::new(data)?,
259                Source::Blank { background } => Image::blank(self.width, self.height, background)?,
260            };
261            for (index, step) in self.steps.iter().enumerate() {
262                if index > 0 {
263                    image.settle();
264                }
265                match step {
266                    Step::Transform(transform) => run(&mut image, transform)?,
267                    Step::Drawing(Drawing::Path { data, color, x, y, scale }) => {
268                        image.fill_path(data, color, *x, *y, *scale)?;
269                    }
270                    Step::Drawing(Drawing::Text { text, font, size, color, x, y }) => {
271                        image.draw_text(text, font, *size, color, *x, *y)?;
272                    }
273                }
274            }
275            image.output(format, quality.map_or(-1, i64::from))
276        })
277    }
278}
279
280fn run(image: &mut Image, transform: &Transform) -> Result<()> {
281    let cropped = transform.width > 0 || transform.height > 0;
282    if cropped || transform.gravity != Gravity::Center || transform.focus.is_some() {
283        image.crop(transform.width, transform.height, transform.gravity, transform.focus)?;
284    }
285    if transform.opacity != 1.0 {
286        image.set_opacity(transform.opacity);
287    }
288    if let Some(background) = &transform.background {
289        image.set_background(background)?;
290    }
291    if let Some((width, color)) = &transform.border {
292        image.set_border(*width, color)?;
293    }
294    if transform.radius > 0 {
295        image.set_border_radius(transform.radius)?;
296    }
297    if transform.rotation != 0 {
298        image.set_rotation(transform.rotation)?;
299    }
300    Ok(())
301}