1use 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#[derive(Debug, Clone, PartialEq)]
18pub struct Transform {
19 pub width: u32,
21 pub height: u32,
23 pub gravity: Gravity,
25 pub focus: Option<FocalPoint>,
27 pub opacity: f64,
29 pub background: Option<String>,
31 pub border: Option<(u32, String)>,
33 pub radius: u32,
35 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#[derive(Debug, Clone)]
57pub enum Drawing {
58 Path {
60 data: String,
62 color: String,
64 x: f64,
66 y: f64,
68 scale: f64,
70 },
71 Text {
73 text: String,
75 font: Arc<[u8]>,
77 size: f64,
79 color: String,
81 x: f64,
83 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#[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
131fn 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 pub fn decode(data: &[u8], limits: Limits) -> Result<Canvas> {
156 Canvas::decode_accepting(data, limits, &[])
157 }
158
159 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 pub fn blank(width: u32, height: u32, background: &str, limits: Limits) -> Result<Canvas> {
182 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 pub fn width(&self) -> u32 {
200 self.width
201 }
202
203 pub fn height(&self) -> u32 {
205 self.height
206 }
207
208 pub fn orientation(&self) -> u32 {
210 self.orientation
211 }
212
213 pub fn format(&self) -> Option<Format> {
215 self.format
216 }
217
218 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 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 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}