Skip to main content

laravel_image/
response.rs

1//! The image response: intervention/image-laravel's `ImageResponseFactory` and the
2//! `response()->image()` macro.
3
4use laravel::http::{IntoResponse, Response, StatusCode};
5
6use crate::encoders::EncoderOptions;
7use crate::error::Result;
8use crate::format::{FileExtension, Format, IntoFormat, MediaType};
9use crate::image::Image;
10
11/// The target format of a response: a [`Format`], [`MediaType`], [`FileExtension`], a string
12/// holding a media type or an extension, or `None` for the image's original format (JPEG when
13/// it has none).
14pub trait ResponseFormat {
15    /// The format for `image`.
16    ///
17    /// # Errors
18    ///
19    /// [`ImageError::InvalidArgument`](crate::ImageError::InvalidArgument) for an unknown string.
20    fn response_format(self, image: &Image) -> Result<Format>;
21}
22
23macro_rules! response_format {
24    ($($type:ty),*) => {$(
25        impl ResponseFormat for $type {
26            fn response_format(self, _: &Image) -> Result<Format> {
27                self.into_format()
28            }
29        }
30    )*};
31}
32
33response_format!(Format, MediaType, FileExtension, &str, &String, String);
34
35impl ResponseFormat for Option<Format> {
36    fn response_format(self, image: &Image) -> Result<Format> {
37        Ok(match self {
38            Some(format) => format,
39            None => Format::try_create(image.origin().media_type()).unwrap_or(Format::Jpeg),
40        })
41    }
42}
43
44/// `Intervention\Image\Laravel\ImageResponseFactory`.
45#[derive(Debug, Clone, Copy, Default)]
46pub struct ImageResponseFactory;
47
48impl ImageResponseFactory {
49    /// `ImageResponseFactory::make($image, $format, ...$options)`: a `200` response with the
50    /// encoded image and its `Content-Type`.
51    ///
52    /// # Errors
53    ///
54    /// An unknown format, or the errors of [`Image::encode_with`].
55    pub fn make(image: &Image, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
56        let format = format.response_format(image)?;
57        let encoded = image.encode_using_media_type(format.media_type(), options)?;
58        let content_type = format.media_type().value();
59        let mut response = (StatusCode::OK, encoded.into_bytes()).into_response();
60        if let Ok(value) = content_type.parse() {
61            response.headers_mut().insert("content-type", value);
62        }
63        Ok(response)
64    }
65}
66
67impl Image {
68    /// `response()->image($image, $format, ...$options)`: the image as an HTTP response.
69    ///
70    /// ```ignore
71    /// use laravel_image::{EncoderOptions, Format, Image};
72    ///
73    /// async fn show() -> laravel::Result<Response> {
74    ///     let mut image = Image::decode(storage::get("example.jpg").await?)?;
75    ///     image.scale(300, 200)?;
76    ///     Ok(image.response(Format::Webp, EncoderOptions::new().quality(65))?)
77    /// }
78    /// ```
79    ///
80    /// # Errors
81    ///
82    /// As [`ImageResponseFactory::make`].
83    pub fn response(&self, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
84        ImageResponseFactory::make(self, format, options)
85    }
86}