laravel_image/
response.rs1use 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
11pub trait ResponseFormat {
15 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#[derive(Debug, Clone, Copy, Default)]
46pub struct ImageResponseFactory;
47
48impl ImageResponseFactory {
49 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 pub fn response(&self, format: impl ResponseFormat, options: EncoderOptions) -> Result<Response> {
84 ImageResponseFactory::make(self, format, options)
85 }
86}