laravel-image 0.2.0

Image handling and manipulation for Laravel Rust, in pure Rust: a port of intervention/image-laravel and Intervention Image.
Documentation
//! The image: Intervention Image's `Image` class, and the `Image` facade's static methods.

use std::path::{Path, PathBuf};
use std::time::Duration;

use image::RgbaImage;

use crate::color::Color;
use crate::config::DriverConfig;
use crate::error::{ImageError, Result};
use crate::exif::Exif;
use crate::format::{Format, MediaType};
use crate::geometry::Size;
use crate::manager::{ImageManager, Source};

/// One frame of an image. Still images have one, animated GIFs one per frame.
#[derive(Debug, Clone)]
pub struct Frame {
    pub(crate) buffer: RgbaImage,
    pub(crate) delay: Duration,
}

impl Frame {
    /// The frame's pixels.
    pub fn buffer(&self) -> &RgbaImage {
        &self.buffer
    }

    /// How long the frame is shown: `$frame->delay()`.
    pub fn delay(&self) -> Duration {
        self.delay
    }
}

/// Where an image came from: Intervention Image's `Origin`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Origin {
    media_type: String,
    file_path: Option<PathBuf>,
}

impl Default for Origin {
    fn default() -> Self {
        Self {
            media_type: "application/octet-stream".to_owned(),
            file_path: None,
        }
    }
}

impl Origin {
    pub(crate) fn new(media_type: MediaType, file_path: Option<PathBuf>) -> Self {
        Self {
            media_type: media_type.value().to_owned(),
            file_path,
        }
    }

    /// The media type of the decoded data; `application/octet-stream` for created images.
    pub fn media_type(&self) -> &str {
        &self.media_type
    }

    /// The path the image was decoded from.
    pub fn file_path(&self) -> Option<&Path> {
        self.file_path.as_deref()
    }

    /// The extension of [`file_path`](Self::file_path).
    pub fn file_extension(&self) -> Option<&str> {
        self.file_path
            .as_deref()?
            .extension()?
            .to_str()
            .filter(|extension| !extension.is_empty())
    }

    /// The format of the media type.
    ///
    /// # Errors
    ///
    /// [`ImageError::NotSupported`] when the media type isn't an image format.
    pub fn format(&self) -> Result<Format> {
        MediaType::create(&self.media_type)
            .map(MediaType::format)
            .map_err(|_| ImageError::NotSupported(format!("Media type \"{}\" is not supported", self.media_type)))
    }
}

/// The color space of an image. The pure-Rust driver works in 8-bit RGB with alpha, like PHP's
/// GD driver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Colorspace {
    Rgb,
}

/// An image: Intervention Image's `Image` class.
///
/// Its static functions are the `Image` facade of intervention/image-laravel, using the
/// application's configuration:
///
/// ```ignore
/// use laravel_image::{Format, Image};
///
/// let mut image = Image::decode("storage/app/example.jpg")?;
/// image.scale(300, 200)?.grayscale();
/// let encoded = image.encode_using_format(Format::Webp, Default::default())?;
/// ```
///
/// Modifiers change the image in place and return it, so they chain as in PHP.
#[derive(Debug, Clone)]
pub struct Image {
    pub(crate) frames: Vec<Frame>,
    pub(crate) loops: u16,
    pub(crate) origin: Origin,
    pub(crate) exif: Exif,
    pub(crate) config: DriverConfig,
}

/// The facade: the configured [`ImageManager`]'s methods.
impl Image {
    /// `Image::decode($source)`: decode a path, binary data, Base64, a data URI, an uploaded file
    /// or another image, with the application's configuration.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode`].
    pub fn decode(source: impl Into<Source>) -> Result<Image> {
        ImageManager::configured().decode(source)
    }

    /// `Image::decodePath($path)`.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode_path`].
    pub fn decode_path(path: impl AsRef<Path>) -> Result<Image> {
        ImageManager::configured().decode_path(path)
    }

    /// `Image::decodeBinary($binary)`.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode_binary`].
    pub fn decode_binary(binary: impl AsRef<[u8]>) -> Result<Image> {
        ImageManager::configured().decode_binary(binary)
    }

    /// `Image::decodeBase64($base64)`.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode_base64`].
    pub fn decode_base64(base64: &str) -> Result<Image> {
        ImageManager::configured().decode_base64(base64)
    }

    /// `Image::decodeDataUri($dataUri)`.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode_data_uri`].
    pub fn decode_data_uri(data_uri: &str) -> Result<Image> {
        ImageManager::configured().decode_data_uri(data_uri)
    }

    /// `Image::decodeSplFileInfo($request->file('image'))`: decode an upload.
    ///
    /// # Errors
    ///
    /// The errors of [`ImageManager::decode_uploaded_file`].
    pub fn decode_uploaded_file(file: &laravel::http::UploadedFile) -> Result<Image> {
        ImageManager::configured().decode_uploaded_file(file)
    }

    /// `Image::createImage($width, $height)`: a new transparent image.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] when a side is smaller than 1.
    pub fn create_image(width: u32, height: u32) -> Result<Image> {
        ImageManager::configured().create_image(width, height)
    }
}

impl Image {
    pub(crate) fn from_frames(frames: Vec<Frame>, config: DriverConfig) -> Image {
        Image {
            frames,
            loops: 0,
            origin: Origin::default(),
            exif: Exif::default(),
            config,
        }
    }

    pub(crate) fn first(&self) -> &RgbaImage {
        &self.frames[0].buffer
    }

    /// The width in pixels.
    pub fn width(&self) -> u32 {
        self.first().width()
    }

    /// The height in pixels.
    pub fn height(&self) -> u32 {
        self.first().height()
    }

    /// The size.
    pub fn size(&self) -> Size {
        Size::of(self.width(), self.height())
    }

    /// The color space.
    pub fn colorspace(&self) -> Colorspace {
        Colorspace::Rgb
    }

    /// Where the image came from.
    pub fn origin(&self) -> &Origin {
        &self.origin
    }

    /// Replace the origin's media type, as `$image->origin()->setMediaType()`.
    pub fn set_origin_media_type(&mut self, media_type: MediaType) -> &mut Self {
        self.origin.media_type = media_type.value().to_owned();
        self
    }

    /// The Exif data read when decoding.
    pub fn exif(&self) -> &Exif {
        &self.exif
    }

    /// Replace the Exif data.
    pub fn set_exif(&mut self, exif: Exif) -> &mut Self {
        self.exif = exif;
        self
    }

    /// The driver options the image was made with.
    pub fn config(&self) -> &DriverConfig {
        &self.config
    }

    /// The frames: `foreach ($image as $frame)`.
    pub fn frames(&self) -> &[Frame] {
        &self.frames
    }

    /// The number of frames.
    pub fn count(&self) -> usize {
        self.frames.len()
    }

    /// More than one frame.
    pub fn is_animated(&self) -> bool {
        self.frames.len() > 1
    }

    /// How often an animation repeats; `0` is forever.
    pub fn loops(&self) -> u16 {
        self.loops
    }

    /// Set how often an animation repeats; `0` is forever.
    pub fn set_loops(&mut self, loops: u16) -> &mut Self {
        self.loops = loops;
        self
    }

    /// `removeAnimation($position)`: keep only the frame at `position`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] when there's no such frame.
    pub fn remove_animation(&mut self, position: usize) -> Result<&mut Self> {
        if position >= self.frames.len() {
            return Err(ImageError::InvalidArgument(format!(
                "Frame #{position} could not be found in the image"
            )));
        }
        let frame = self.frames.swap_remove(position);
        self.frames = vec![frame];
        Ok(self)
    }

    /// The color of a pixel of a frame: `colorAt($x, $y, $frame)`.
    pub fn color_at(&self, x: u32, y: u32, frame: usize) -> Option<Color> {
        let buffer = &self.frames.get(frame)?.buffer;
        (x < buffer.width() && y < buffer.height()).then(|| Color::from_pixel(*buffer.get_pixel(x, y)))
    }

    /// The image's background color: `backgroundColor()`, from the configuration.
    ///
    /// # Errors
    ///
    /// [`ImageError::ColorDecoder`] when the configured color can't be decoded.
    pub fn background_color(&self) -> Result<Color> {
        self.config.background()
    }

    /// Set the background color: `setBackgroundColor()`.
    pub fn set_background_color(&mut self, color: &str) -> Result<&mut Self> {
        Color::parse(color)?;
        self.config.background_color = color.to_owned();
        Ok(self)
    }

    pub(crate) fn map_frames(&mut self, mut f: impl FnMut(&RgbaImage) -> RgbaImage) {
        for frame in &mut self.frames {
            frame.buffer = f(&frame.buffer);
        }
    }

    pub(crate) fn each_frame(&mut self, mut f: impl FnMut(&mut RgbaImage)) {
        for frame in &mut self.frames {
            f(&mut frame.buffer);
        }
    }
}