1use 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#[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
63fn div(a: f64, b: f64) -> Result<f64> {
65 if b == 0.0 { Err(Error::DivisionByZero) } else { Ok(a / b) }
66}
67
68fn intval(v: f64) -> i64 {
70 dval_to_lval(v)
71}
72
73impl Image {
74 pub fn new(data: &[u8]) -> Result<Image> {
84 let format = Format::detect(data)?;
86 let frames = decode::decode(data, format)?;
87 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 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 pub fn orientation(&self) -> u32 {
148 self.orientation
149 }
150
151 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 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 pub fn width(&self) -> i64 {
175 self.width
176 }
177
178 pub fn height(&self) -> i64 {
180 self.height
181 }
182
183 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 pub fn frames(&self) -> usize {
193 self.frames.len()
194 }
195
196 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 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 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 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 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 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 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 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 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 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 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 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 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 OutputFormat::Png => {
454 frame.format = Format::Png;
455 }
456 }
457 Ok(())
458 }
459
460 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 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 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 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
494fn 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
525fn 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}