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};
#[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>,
}
fn div(a: f64, b: f64) -> Result<f64> {
if b == 0.0 { Err(Error::DivisionByZero) } else { Ok(a / b) }
}
fn intval(v: f64) -> i64 {
dval_to_lval(v)
}
impl Image {
pub fn new(data: &[u8]) -> Result<Image> {
let format = Format::detect(data)?;
let frames = decode::decode(data, format)?;
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,
})
}
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,
})
}
pub fn orientation(&self) -> u32 {
self.orientation
}
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)
}
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)
}
pub fn width(&self) -> i64 {
self.width
}
pub fn height(&self) -> i64 {
self.height
}
pub(crate) fn settle(&mut self) {
let frame = &self.frames[self.current];
(self.width, self.height) = (i64::from(frame.width()), i64::from(frame.height()));
}
pub fn frames(&self) -> usize {
self.frames.len()
}
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)?;
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 {
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)
}
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)
}
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 {
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)
}
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
}
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)
}
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)
}
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)
}
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);
}
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(())
}
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;
}
OutputFormat::Png => {
frame.format = Format::Png;
}
}
Ok(())
}
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);
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))
}
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))
}
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))
}
}
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),
}
}
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)
}