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 response: intervention/image-laravel's `ImageResponseFactory` and the
//! `response()->image()` macro.

use laravel::http::{IntoResponse, Response, StatusCode};

use crate::encoders::EncoderOptions;
use crate::error::Result;
use crate::format::{FileExtension, Format, IntoFormat, MediaType};
use crate::image::Image;

/// The target format of a response: a [`Format`], [`MediaType`], [`FileExtension`], a string
/// holding a media type or an extension, or `None` for the image's original format (JPEG when
/// it has none).
pub trait ResponseFormat {
    /// The format for `image`.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`](crate::ImageError::InvalidArgument) for an unknown string.
    fn response_format(self, image: &Image) -> Result<Format>;
}

macro_rules! response_format {
    ($($type:ty),*) => {$(
        impl ResponseFormat for $type {
            fn response_format(self, _: &Image) -> Result<Format> {
                self.into_format()
            }
        }
    )*};
}

response_format!(Format, MediaType, FileExtension, &str, &String, String);

impl ResponseFormat for Option<Format> {
    fn response_format(self, image: &Image) -> Result<Format> {
        Ok(match self {
            Some(format) => format,
            None => Format::try_create(image.origin().media_type()).unwrap_or(Format::Jpeg),
        })
    }
}

/// `Intervention\Image\Laravel\ImageResponseFactory`.
#[derive(Debug, Clone, Copy, Default)]
pub struct ImageResponseFactory;

impl ImageResponseFactory {
    /// `ImageResponseFactory::make($image, $format, ...$options)`: a `200` response with the
    /// encoded image and its `Content-Type`.
    ///
    /// # Errors
    ///
    /// An unknown format, or the errors of [`Image::encode_with`].
    pub fn make(image: &Image, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
        let format = format.response_format(image)?;
        let encoded = image.encode_using_media_type(format.media_type(), options)?;
        let content_type = format.media_type().value();
        let mut response = (StatusCode::OK, encoded.into_bytes()).into_response();
        if let Ok(value) = content_type.parse() {
            response.headers_mut().insert("content-type", value);
        }
        Ok(response)
    }
}

impl Image {
    /// `response()->image($image, $format, ...$options)`: the image as an HTTP response.
    ///
    /// ```ignore
    /// use laravel_image::{EncoderOptions, Format, Image};
    ///
    /// async fn show() -> laravel::Result<Response> {
    ///     let mut image = Image::decode(storage::get("example.jpg").await?)?;
    ///     image.scale(300, 200)?;
    ///     Ok(image.response(Format::Webp, EncoderOptions::new().quality(65))?)
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// As [`ImageResponseFactory::make`].
    pub fn response(&self, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
        ImageResponseFactory::make(self, format, options)
    }
}