Skip to main content

larastvel_core/image/
mod.rs

1//! Image manipulation — Laravel 13.20's `Image` facade.
2//!
3//! Images are immutable: every transformation returns a new instance with the
4//! operation appended to its pipeline, and processing happens once at encode
5//! time. Backed by the `image` crate (Rust equivalent of Intervention Image).
6
7use std::io::Cursor;
8use std::path::Path;
9use std::sync::Mutex;
10
11use base64::Engine as _;
12use image::imageops::FilterType;
13use image::{DynamicImage, ImageFormat};
14
15/// Errors produced while reading, transforming, or encoding images.
16#[derive(Debug, thiserror::Error)]
17pub enum ImageError {
18    #[error("invalid base64 image data")]
19    InvalidBase64,
20    #[error("failed to read image: {0}")]
21    Read(String),
22    #[error("failed to decode image: {0}")]
23    Decode(String),
24    #[error("failed to encode image: {0}")]
25    Encode(String),
26    #[error("the [{0}] format is not supported")]
27    UnsupportedFormat(String),
28    #[error("unable to determine the dimensions of the image")]
29    Dimensions,
30    #[error("at least one resize dimension must be specified")]
31    ResizeDimensions,
32    #[error("invalid storage path `{0}`: path must stay within the storage directory")]
33    InvalidStoragePath(String),
34    #[error("failed to write image: {0}")]
35    Write(String),
36}
37
38pub type Result<T> = std::result::Result<T, ImageError>;
39
40/// Output formats supported by [`ImageInstance::to_*`] conversions.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum OutputFormat {
43    Png,
44    Jpeg,
45    Gif,
46    Webp,
47    Bmp,
48}
49
50impl OutputFormat {
51    pub fn mime_type(self) -> &'static str {
52        match self {
53            Self::Png => "image/png",
54            Self::Jpeg => "image/jpeg",
55            Self::Gif => "image/gif",
56            Self::Webp => "image/webp",
57            Self::Bmp => "image/bmp",
58        }
59    }
60
61    pub fn extension(self) -> &'static str {
62        match self {
63            Self::Png => "png",
64            Self::Jpeg => "jpg",
65            Self::Gif => "gif",
66            Self::Webp => "webp",
67            Self::Bmp => "bmp",
68        }
69    }
70}
71
72/// Background fill used by [`ImageInstance::contain`] and
73/// [`ImageInstance::rotate`].
74#[derive(Debug, Clone, PartialEq)]
75pub enum Background {
76    /// A hex color such as `#ffffff` (or a bare name like `white`).
77    Hex(String),
78    /// The image's dominant color.
79    Dominant,
80}
81
82impl Background {
83    fn to_rgba(&self, dominant: [u8; 3]) -> image::Rgba<u8> {
84        match self {
85            Self::Dominant => image::Rgba([dominant[0], dominant[1], dominant[2], 255]),
86            Self::Hex(hex) => parse_hex_color(hex)
87                .map(|[r, g, b]| image::Rgba([r, g, b, 255]))
88                .unwrap_or(image::Rgba([255, 255, 255, 255])),
89        }
90    }
91}
92
93fn parse_hex_color(s: &str) -> Option<[u8; 3]> {
94    let s = s.trim_start_matches('#');
95    match s.len() {
96        6 => {
97            let v = u32::from_str_radix(s, 16).ok()?;
98            Some([(v >> 16) as u8, (v >> 8) as u8, v as u8])
99        }
100        3 => {
101            let v = u32::from_str_radix(s, 16).ok()?;
102            let r = (v >> 8) as u8;
103            let g = ((v >> 4) & 0xF) as u8;
104            let b = (v & 0xF) as u8;
105            Some([r * 17, g * 17, b * 17])
106        }
107        _ => None,
108    }
109}
110
111/// A single transformation queued on the processing pipeline.
112#[derive(Debug, Clone, PartialEq)]
113pub enum Op {
114    Resize(Option<u32>, Option<u32>),
115    Scale(Option<u32>, Option<u32>),
116    Cover(u32, u32),
117    Contain(u32, u32, Option<Background>),
118    Crop(u32, u32, u32, u32),
119    Rotate(f32, Option<Background>),
120    Orient,
121    Blur(u8),
122    Grayscale,
123    Sharpen(u8),
124    FlipVertically,
125    FlipHorizontally,
126}
127
128/// An immutable image with a queue of pending transformations.
129///
130/// Mirrors `Illuminate\Image\Image`: transformations are chained fluently,
131/// processed in order, and the image is only encoded once at the end.
132#[derive(Debug, Clone)]
133pub struct ImageInstance {
134    contents: Vec<u8>,
135    source_name: Option<String>,
136    original_format: ImageFormat,
137    ops: Vec<Op>,
138    format: Option<OutputFormat>,
139    quality: u8,
140}
141
142impl ImageInstance {
143    fn new(contents: Vec<u8>, source_name: Option<String>) -> Result<Self> {
144        let format =
145            image::guess_format(&contents).map_err(|e| ImageError::Decode(e.to_string()))?;
146        Ok(Self {
147            contents,
148            source_name,
149            original_format: format,
150            ops: Vec::new(),
151            format: None,
152            quality: 70,
153        })
154    }
155
156    fn with_op(&self, op: Op) -> Self {
157        let mut clone = self.clone();
158        clone.ops.push(op);
159        record_fake(&clone);
160        clone
161    }
162
163    /// Resize the image to the given dimensions. Either width or height may
164    /// be omitted to preserve the aspect ratio.
165    pub fn resize(&self, width: Option<u32>, height: Option<u32>) -> Result<Self> {
166        if width.is_none() && height.is_none() {
167            return Err(ImageError::ResizeDimensions);
168        }
169        Ok(self.with_op(Op::Resize(width, height)))
170    }
171
172    /// Proportionally scale the image down so it fits within the given
173    /// dimensions. Never increases the image size.
174    pub fn scale(&self, width: Option<u32>, height: Option<u32>) -> Result<Self> {
175        if width.is_none() && height.is_none() {
176            return Err(ImageError::ResizeDimensions);
177        }
178        Ok(self.with_op(Op::Scale(width, height)))
179    }
180
181    /// Resize and crop the image to completely cover the given dimensions.
182    pub fn cover(&self, width: u32, height: u32) -> Self {
183        self.with_op(Op::Cover(width.max(1), height.max(1)))
184    }
185
186    /// Resize the image to fit within the given dimensions while preserving
187    /// the entire image. Empty space is filled with the optional background
188    /// color (`"#ffffff"`, `"dominant"`, or `None` for transparent).
189    pub fn contain(&self, width: u32, height: u32, background: Option<&str>) -> Self {
190        let background = background.map(|b| {
191            if b.eq_ignore_ascii_case("dominant") {
192                Background::Dominant
193            } else {
194                Background::Hex(b.to_string())
195            }
196        });
197        self.with_op(Op::Contain(width.max(1), height.max(1), background))
198    }
199
200    /// Crop the image to the given dimensions and position.
201    pub fn crop(&self, width: u32, height: u32, x: u32, y: u32) -> Self {
202        self.with_op(Op::Crop(width.max(1), height.max(1), x, y))
203    }
204
205    /// Rotate the image clockwise by the given angle (degrees), filling the
206    /// background with the optional color (`"#ffffff"` / `"dominant"`).
207    pub fn rotate(&self, angle: f32, background: Option<&str>) -> Self {
208        let background = background.map(|b| {
209            if b.eq_ignore_ascii_case("dominant") {
210                Background::Dominant
211            } else {
212                Background::Hex(b.to_string())
213            }
214        });
215        self.with_op(Op::Rotate(angle, background))
216    }
217
218    /// Auto-orient the image based on its EXIF orientation data.
219    pub fn orient(&self) -> Self {
220        self.with_op(Op::Orient)
221    }
222
223    /// Apply a gaussian blur. `amount` is clamped between 0 and 100.
224    pub fn blur(&self, amount: u8) -> Self {
225        self.with_op(Op::Blur(amount.min(100)))
226    }
227
228    /// Convert the image to grayscale.
229    pub fn grayscale(&self) -> Self {
230        self.with_op(Op::Grayscale)
231    }
232
233    /// Sharpen the image (unsharp mask). `amount` is clamped between 0 and 100.
234    pub fn sharpen(&self, amount: u8) -> Self {
235        self.with_op(Op::Sharpen(amount.min(100)))
236    }
237
238    /// Flip the image vertically.
239    pub fn flip_vertically(&self) -> Self {
240        self.with_op(Op::FlipVertically)
241    }
242
243    /// Flip the image horizontally.
244    pub fn flip_horizontally(&self) -> Self {
245        self.with_op(Op::FlipHorizontally)
246    }
247
248    /// Flip the image vertically (`flip`).
249    pub fn flip(&self) -> Self {
250        self.flip_vertically()
251    }
252
253    /// Flip the image horizontally (`flop`).
254    pub fn flop(&self) -> Self {
255        self.flip_horizontally()
256    }
257
258    /// Set the output quality, clamped between 1 and 100. Applies to lossy
259    /// encoders (JPEG); other encoders use their default settings.
260    pub fn quality(&self, quality: u8) -> Self {
261        let mut clone = self.clone();
262        clone.quality = quality.clamp(1, 100);
263        clone
264    }
265
266    /// Convert the image to WebP format.
267    pub fn to_webp(&self) -> Self {
268        self.to_format(OutputFormat::Webp)
269    }
270
271    /// Convert the image to JPEG format.
272    pub fn to_jpg(&self) -> Self {
273        self.to_format(OutputFormat::Jpeg)
274    }
275
276    /// Convert the image to JPEG format.
277    pub fn to_jpeg(&self) -> Self {
278        self.to_jpg()
279    }
280
281    /// Convert the image to PNG format.
282    pub fn to_png(&self) -> Self {
283        self.to_format(OutputFormat::Png)
284    }
285
286    /// Convert the image to GIF format.
287    pub fn to_gif(&self) -> Self {
288        self.to_format(OutputFormat::Gif)
289    }
290
291    /// Convert the image to BMP format.
292    pub fn to_bmp(&self) -> Self {
293        self.to_format(OutputFormat::Bmp)
294    }
295
296    /// Convert the image to the given format.
297    pub fn to_format(&self, format: OutputFormat) -> Self {
298        let mut clone = self.clone();
299        clone.format = Some(format);
300        record_fake(&clone);
301        clone
302    }
303
304    /// Convenience for converting to a format and setting quality.
305    pub fn optimize(&self, format: OutputFormat, quality: u8) -> Self {
306        self.to_format(format).quality(quality)
307    }
308
309    /// Process the image and return the raw bytes.
310    pub fn to_bytes(&self) -> Result<Vec<u8>> {
311        if self.ops.is_empty() && self.format.is_none() {
312            return Ok(self.contents.clone());
313        }
314        let decoded = image::load_from_memory(&self.contents)
315            .map_err(|e| ImageError::Decode(e.to_string()))?;
316        let img = self.apply_ops(decoded)?;
317        let format = self.format.unwrap_or(original_format(self.original_format));
318        encode(&img, format, self.quality)
319    }
320
321    /// Process the image and return it as a base64 encoded string.
322    pub fn to_base64(&self) -> Result<String> {
323        Ok(base64::engine::general_purpose::STANDARD.encode(self.to_bytes()?))
324    }
325
326    /// Process the image and return it as a data URI.
327    pub fn to_data_uri(&self) -> Result<String> {
328        Ok(format!(
329            "data:{};base64,{}",
330            self.mime_type()?,
331            self.to_base64()?
332        ))
333    }
334
335    /// The MIME type of the processed image.
336    pub fn mime_type(&self) -> Result<String> {
337        Ok(self
338            .format
339            .map(|f| f.mime_type().to_string())
340            .unwrap_or_else(|| mime_type_for(self.original_format).to_string()))
341    }
342
343    /// The file extension of the processed image.
344    pub fn extension(&self) -> String {
345        self.format
346            .map(|f| f.extension().to_string())
347            .unwrap_or_else(|| extension_for(self.original_format).to_string())
348    }
349
350    /// The dimensions of the processed image as `(width, height)`.
351    pub fn dimensions(&self) -> Result<(u32, u32)> {
352        let decoded = image::load_from_memory(&self.contents)
353            .map_err(|e| ImageError::Decode(e.to_string()))?;
354        let img = self.apply_ops(decoded)?;
355        Ok((img.width(), img.height()))
356    }
357
358    /// The width of the processed image.
359    pub fn width(&self) -> Result<u32> {
360        Ok(self.dimensions()?.0)
361    }
362
363    /// The height of the processed image.
364    pub fn height(&self) -> Result<u32> {
365        Ok(self.dimensions()?.1)
366    }
367
368    /// The dominant (average) color of the processed image as a hex string.
369    pub fn dominant_color(&self) -> Result<String> {
370        let decoded = image::load_from_memory(&self.contents)
371            .map_err(|e| ImageError::Decode(e.to_string()))?;
372        let img = self.apply_ops(decoded)?;
373        let rgb = img.to_rgb8();
374        let (mut r, mut g, mut b, mut count) = (0u64, 0u64, 0u64, 0u64);
375        for pixel in rgb.pixels() {
376            r += pixel[0] as u64;
377            g += pixel[1] as u64;
378            b += pixel[2] as u64;
379            count += 1;
380        }
381        if count == 0 {
382            return Err(ImageError::Dimensions);
383        }
384        Ok(format!(
385            "#{:02x}{:02x}{:02x}",
386            (r / count) as u8,
387            (g / count) as u8,
388            (b / count) as u8
389        ))
390    }
391
392    /// Write the processed image to `path`, creating parent directories.
393    /// Returns the path on success.
394    pub fn save(&self, path: &Path) -> Result<String> {
395        let bytes = self.to_bytes()?;
396        if let Some(parent) = path.parent() {
397            std::fs::create_dir_all(parent).map_err(|e| ImageError::Write(e.to_string()))?;
398        }
399        std::fs::write(path, &bytes).map_err(|e| ImageError::Write(e.to_string()))?;
400        Ok(path.to_string_lossy().into_owned())
401    }
402
403    /// Store the processed image on the local disk under `storage/app`.
404    /// Returns the relative stored path.
405    pub fn store(&self, path: &str) -> Result<String> {
406        self.store_as(path, &self.hash_name())
407    }
408
409    /// Store the processed image on the local disk under `storage/app`
410    /// with the given name. Returns the relative stored path.
411    pub fn store_as(&self, path: &str, name: &str) -> Result<String> {
412        if path.split('/').any(|seg| seg == "..") || name.split('/').any(|seg| seg == "..") {
413            return Err(ImageError::InvalidStoragePath(format!("{path}/{name}")));
414        }
415        let root = crate::storage_path(Some("app"));
416        let dir = if path.is_empty() {
417            root.clone()
418        } else {
419            root.join(path)
420        };
421        std::fs::create_dir_all(&dir).map_err(|e| ImageError::Write(e.to_string()))?;
422        let full = dir.join(name);
423        std::fs::write(&full, self.to_bytes()?).map_err(|e| ImageError::Write(e.to_string()))?;
424        let relative = if path.is_empty() {
425            name.to_string()
426        } else {
427            format!("{}/{}", path.trim_end_matches('/'), name)
428        };
429        let mut state = fake_state().lock().unwrap();
430        if let Some(records) = state.as_mut() {
431            let image_name = self
432                .source_name
433                .clone()
434                .unwrap_or_else(|| "image".to_string());
435            records.push(RecordedOp {
436                name: image_name,
437                op: Op::Grayscale,
438                format: None,
439                quality: None,
440                stored_to: Some(relative.clone()),
441            });
442        }
443        Ok(relative)
444    }
445
446    /// Store the processed image with public visibility. The local disk does
447    /// not model visibility, so this is equivalent to [`store`](Self::store).
448    pub fn store_publicly(&self, path: &str) -> Result<String> {
449        self.store(path)
450    }
451
452    /// Store the processed image with public visibility and a given name.
453    pub fn store_publicly_as(&self, path: &str, name: &str) -> Result<String> {
454        self.store_as(path, name)
455    }
456
457    /// A hashed filename with the correct extension (40 random hex chars).
458    pub fn hash_name(&self) -> String {
459        let mut bytes = [0u8; 20];
460        use rand::RngCore;
461        rand::thread_rng().fill_bytes(&mut bytes);
462        format!("{}.{}", hex::encode(bytes), self.extension())
463    }
464
465    fn apply_ops(&self, img: DynamicImage) -> Result<DynamicImage> {
466        let mut img = img;
467        for op in &self.ops {
468            img = apply_op(img, op)?;
469        }
470        Ok(img)
471    }
472}
473
474fn apply_op(img: DynamicImage, op: &Op) -> Result<DynamicImage> {
475    match op {
476        Op::Resize(width, height) => {
477            let (w, h) = resolve_dimensions(img.width(), img.height(), *width, *height)?;
478            Ok(img.resize(w, h, FilterType::Triangle))
479        }
480        Op::Scale(width, height) => {
481            let (w, h) = resolve_dimensions(img.width(), img.height(), *width, *height)?;
482            let ratio = (w as f64 / img.width() as f64)
483                .min(h as f64 / img.height() as f64)
484                .min(1.0);
485            let new_w = (img.width() as f64 * ratio).round().max(1.0) as u32;
486            let new_h = (img.height() as f64 * ratio).round().max(1.0) as u32;
487            Ok(img.resize(new_w, new_h, FilterType::Triangle))
488        }
489        Op::Cover(w, h) => {
490            let ratio = (*w as f64 / img.width() as f64)
491                .max(*h as f64 / img.height() as f64)
492                .max(1.0);
493            let new_w = (img.width() as f64 * ratio).round() as u32;
494            let new_h = (img.height() as f64 * ratio).round() as u32;
495            let resized = img.resize(new_w, new_h, FilterType::Triangle);
496            let x = ((new_w - w) / 2).min(new_w.saturating_sub(*w));
497            let y = ((new_h - h) / 2).min(new_h.saturating_sub(*h));
498            Ok(image::imageops::crop_imm(&resized, x, y, *w, *h)
499                .to_image()
500                .into())
501        }
502        Op::Contain(w, h, background) => {
503            let ratio = (*w as f64 / img.width() as f64)
504                .min(*h as f64 / img.height() as f64)
505                .min(1.0);
506            let new_w = (img.width() as f64 * ratio).round().max(1.0) as u32;
507            let new_h = (img.height() as f64 * ratio).round().max(1.0) as u32;
508            let resized = img.resize(new_w, new_h, FilterType::Triangle);
509            let dominant = dominant_rgb(&resized);
510            let mut canvas = DynamicImage::new_rgba8(*w, *h).to_rgba8();
511            let bg = background
512                .as_ref()
513                .map(|b| b.to_rgba(dominant))
514                .unwrap_or(image::Rgba([0, 0, 0, 0]));
515            for pixel in canvas.pixels_mut() {
516                *pixel = bg;
517            }
518            let x = (*w - new_w) / 2;
519            let y = (*h - new_h) / 2;
520            image::imageops::overlay(&mut canvas, &resized.to_rgba8(), x as i64, y as i64);
521            Ok(canvas.into())
522        }
523        Op::Crop(w, h, x, y) => {
524            let x = (*x).min(img.width().saturating_sub(*w));
525            let y = (*y).min(img.height().saturating_sub(*h));
526            Ok(image::imageops::crop_imm(&img, x, y, *w, *h)
527                .to_image()
528                .into())
529        }
530        Op::Rotate(angle, background) => rotate_cw(
531            &img,
532            *angle,
533            background.as_ref().map(|b| {
534                let dominant = dominant_rgb(&img);
535                b.to_rgba(dominant)
536            }),
537        ),
538        Op::Orient => Ok(img),
539        Op::Blur(amount) => {
540            if *amount == 0 {
541                Ok(img)
542            } else {
543                Ok(image::imageops::blur(&img, f32::from(*amount) * 0.5).into())
544            }
545        }
546        Op::Grayscale => Ok(image::imageops::grayscale(&img).into()),
547        Op::Sharpen(amount) => {
548            if *amount == 0 {
549                Ok(img)
550            } else {
551                Ok(unsharp_mask(&img, *amount))
552            }
553        }
554        Op::FlipVertically => Ok(image::imageops::flip_vertical(&img).into()),
555        Op::FlipHorizontally => Ok(image::imageops::flip_horizontal(&img).into()),
556    }
557}
558
559fn resolve_dimensions(
560    current_w: u32,
561    current_h: u32,
562    width: Option<u32>,
563    height: Option<u32>,
564) -> Result<(u32, u32)> {
565    match (width, height) {
566        (Some(w), Some(h)) => Ok((w, h)),
567        (Some(w), None) => {
568            let ratio = w as f64 / current_w as f64;
569            Ok((w, ((current_h as f64 * ratio).round().max(1.0)) as u32))
570        }
571        (None, Some(h)) => {
572            let ratio = h as f64 / current_h as f64;
573            Ok((((current_w as f64 * ratio).round().max(1.0)) as u32, h))
574        }
575        (None, None) => Err(ImageError::ResizeDimensions),
576    }
577}
578
579fn dominant_rgb(img: &DynamicImage) -> [u8; 3] {
580    let rgb = img.to_rgb8();
581    let (mut r, mut g, mut b, mut count) = (0u64, 0u64, 0u64, 0u64);
582    for pixel in rgb.pixels() {
583        r += pixel[0] as u64;
584        g += pixel[1] as u64;
585        b += pixel[2] as u64;
586        count += 1;
587    }
588    if count == 0 {
589        return [0, 0, 0];
590    }
591    [(r / count) as u8, (g / count) as u8, (b / count) as u8]
592}
593
594/// Rotate clockwise by an arbitrary angle using nearest-neighbor inverse
595/// mapping; multiples of 90° are exact via `imageops`.
596fn rotate_cw(
597    img: &DynamicImage,
598    angle: f32,
599    background: Option<image::Rgba<u8>>,
600) -> Result<DynamicImage> {
601    let normalized = angle.rem_euclid(360.0);
602    if normalized == 0.0 {
603        return Ok(img.clone());
604    }
605    if normalized == 90.0 {
606        return Ok(image::imageops::rotate90(img).into());
607    }
608    if normalized == 180.0 {
609        return Ok(image::imageops::rotate180(img).into());
610    }
611    if normalized == 270.0 {
612        return Ok(image::imageops::rotate270(img).into());
613    }
614    let (w, h) = (img.width(), img.height());
615    let theta = normalized.to_radians();
616    let (sin, cos) = theta.sin_cos();
617    let new_w = ((w as f32 * cos.abs()) + (h as f32 * sin.abs())).ceil() as u32;
618    let new_h = ((w as f32 * sin.abs()) + (h as f32 * cos.abs())).ceil() as u32;
619    let src = img.to_rgba8();
620    let bg = background.unwrap_or(image::Rgba([255, 255, 255, 255]));
621    let mut out = DynamicImage::new_rgba8(new_w.max(1), new_h.max(1)).to_rgba8();
622    for pixel in out.pixels_mut() {
623        *pixel = bg;
624    }
625    let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
626    let (ocx, ocy) = (new_w as f32 / 2.0, new_h as f32 / 2.0);
627    for y in 0..new_h {
628        for x in 0..new_w {
629            let dx = x as f32 - ocx;
630            let dy = y as f32 - ocy;
631            let sx = (dx * cos + dy * sin + cx).round();
632            let sy = (-dx * sin + dy * cos + cy).round();
633            if sx >= 0.0 && sy >= 0.0 && sx < w as f32 && sy < h as f32 {
634                out.put_pixel(x, y, *src.get_pixel(sx as u32, sy as u32));
635            }
636        }
637    }
638    Ok(out.into())
639}
640
641/// Unsharp mask: `out = original + amount * (original - blurred)`.
642fn unsharp_mask(img: &DynamicImage, amount: u8) -> DynamicImage {
643    let blurred = image::imageops::blur(img, 2.0);
644    let mut sharpened = img.to_rgba8();
645    let factor = f32::from(amount) / 100.0;
646    for (out_pixel, blur_pixel) in sharpened.pixels_mut().zip(blurred.pixels()) {
647        for channel in 0..3 {
648            let orig = out_pixel[channel] as f32;
649            let blur = blur_pixel[channel] as f32;
650            let value = (orig + factor * (orig - blur)).clamp(0.0, 255.0);
651            out_pixel[channel] = value as u8;
652        }
653    }
654    sharpened.into()
655}
656
657fn original_format(format: ImageFormat) -> OutputFormat {
658    match format {
659        ImageFormat::Png => OutputFormat::Png,
660        ImageFormat::Jpeg => OutputFormat::Jpeg,
661        ImageFormat::Gif => OutputFormat::Gif,
662        ImageFormat::WebP => OutputFormat::Webp,
663        ImageFormat::Bmp => OutputFormat::Bmp,
664        _ => OutputFormat::Png,
665    }
666}
667
668fn mime_type_for(format: ImageFormat) -> &'static str {
669    match format {
670        ImageFormat::Png => "image/png",
671        ImageFormat::Jpeg => "image/jpeg",
672        ImageFormat::Gif => "image/gif",
673        ImageFormat::WebP => "image/webp",
674        ImageFormat::Bmp => "image/bmp",
675        ImageFormat::Tiff => "image/tiff",
676        _ => "application/octet-stream",
677    }
678}
679
680fn extension_for(format: ImageFormat) -> &'static str {
681    match format {
682        ImageFormat::Png => "png",
683        ImageFormat::Jpeg => "jpg",
684        ImageFormat::Gif => "gif",
685        ImageFormat::WebP => "webp",
686        ImageFormat::Bmp => "bmp",
687        ImageFormat::Tiff => "tiff",
688        _ => "bin",
689    }
690}
691
692fn encode(img: &DynamicImage, format: OutputFormat, quality: u8) -> Result<Vec<u8>> {
693    let mut buf = Cursor::new(Vec::new());
694    match format {
695        OutputFormat::Jpeg => {
696            let encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality);
697            img.write_with_encoder(encoder)
698                .map_err(|e| ImageError::Encode(e.to_string()))?;
699        }
700        OutputFormat::Png => {
701            img.write_to(&mut buf, ImageFormat::Png)
702                .map_err(|e| ImageError::Encode(e.to_string()))?;
703        }
704        OutputFormat::Gif => {
705            img.write_to(&mut buf, ImageFormat::Gif)
706                .map_err(|e| ImageError::Encode(e.to_string()))?;
707        }
708        OutputFormat::Webp => {
709            img.write_to(&mut buf, ImageFormat::WebP)
710                .map_err(|e| ImageError::Encode(e.to_string()))?;
711        }
712        OutputFormat::Bmp => {
713            img.write_to(&mut buf, ImageFormat::Bmp)
714                .map_err(|e| ImageError::Encode(e.to_string()))?;
715        }
716    }
717    Ok(buf.into_inner())
718}
719
720/// A recorded image operation for the test fake.
721#[derive(Debug, Clone, PartialEq)]
722pub struct RecordedOp {
723    pub name: String,
724    pub op: Op,
725    pub format: Option<OutputFormat>,
726    pub quality: Option<u8>,
727    pub stored_to: Option<String>,
728}
729
730/// Global fake state used by [`Image::fake`] and the `assert_*` helpers.
731static FAKE_STATE: std::sync::OnceLock<Mutex<Option<Vec<RecordedOp>>>> = std::sync::OnceLock::new();
732
733fn fake_state() -> &'static Mutex<Option<Vec<RecordedOp>>> {
734    FAKE_STATE.get_or_init(|| Mutex::new(None))
735}
736
737/// The `Image` facade — Laravel 13.20's first-party image processing.
738///
739/// ```rust,ignore
740/// let image = Image::from_path("input.jpg")?.cover(400, 400)?.to_webp()?;
741/// image.save("output.webp")?;
742/// ```
743pub struct Image;
744
745impl Image {
746    /// Create an image instance from raw bytes.
747    pub fn from_bytes(contents: &[u8]) -> Result<ImageInstance> {
748        ImageInstance::new(contents.to_vec(), None)
749    }
750
751    /// Create an image instance from a base64 encoded string.
752    pub fn from_base64(base64: &str) -> Result<ImageInstance> {
753        let decoded = base64::engine::general_purpose::STANDARD
754            .decode(base64)
755            .map_err(|_| ImageError::InvalidBase64)?;
756        ImageInstance::new(decoded, None)
757    }
758
759    /// Create an image instance from a file path.
760    pub fn from_path(path: &str) -> Result<ImageInstance> {
761        let bytes = std::fs::read(path).map_err(|e| ImageError::Read(e.to_string()))?;
762        let name = Path::new(path)
763            .file_name()
764            .map(|n| n.to_string_lossy().into_owned());
765        ImageInstance::new(bytes, name)
766    }
767
768    /// Create an image instance from a URL. The URL is fetched over HTTP.
769    pub async fn from_url(url: &str) -> Result<ImageInstance> {
770        let bytes = reqwest::get(url)
771            .await
772            .map_err(|e| ImageError::Read(e.to_string()))?
773            .bytes()
774            .await
775            .map_err(|e| ImageError::Read(e.to_string()))?
776            .to_vec();
777        ImageInstance::new(bytes, Some(url.to_string()))
778    }
779
780    /// Create an image instance from a storage disk path (relative to the
781    /// application's `storage/app` directory).
782    pub fn from_storage(path: &str) -> Result<ImageInstance> {
783        let root = crate::storage_path(Some("app"));
784        Image::from_path(&root.join(path).to_string_lossy())
785    }
786
787    /// Swap the image processing pipeline with a fake that records
788    /// operations instead of performing them. Returns the previous fake
789    /// state so callers can restore it.
790    pub fn fake() -> bool {
791        let mut state = fake_state().lock().unwrap();
792        let was_faked = state.is_some();
793        *state = Some(Vec::new());
794        was_faked
795    }
796
797    /// Restore real image processing (turns the fake off).
798    pub fn restore() {
799        let mut state = fake_state().lock().unwrap();
800        *state = None;
801    }
802
803    /// Whether image processing is currently faked.
804    pub fn is_faked() -> bool {
805        fake_state().lock().unwrap().is_some()
806    }
807
808    /// Assert that an image was resized to the given dimensions.
809    pub fn assert_resized(name: &str, width: Option<u32>, height: Option<u32>) {
810        Self::assert_recorded(
811            name,
812            |r| matches!(r.op, Op::Resize(w, h) if w == width && h == height),
813        );
814    }
815
816    /// Assert that an image was covered to the given dimensions.
817    pub fn assert_covered(name: &str, width: u32, height: u32) {
818        Self::assert_recorded(
819            name,
820            |r| matches!(r.op, Op::Cover(w, h) if w == width && h == height),
821        );
822    }
823
824    /// Assert that an image was cropped to the given dimensions and position.
825    pub fn assert_cropped(name: &str, width: u32, height: u32, x: u32, y: u32) {
826        Self::assert_recorded(
827            name,
828            |r| matches!(r.op, Op::Crop(w, h, cx, cy) if w == width && h == height && cx == x && cy == y),
829        );
830    }
831
832    /// Assert that an image was contained to the given dimensions.
833    pub fn assert_contained(name: &str, width: u32, height: u32) {
834        Self::assert_recorded(
835            name,
836            |r| matches!(r.op, Op::Contain(w, h, _) if w == width && h == height),
837        );
838    }
839
840    /// Assert that an image was rotated by the given angle.
841    pub fn assert_rotated(name: &str, angle: f32) {
842        Self::assert_recorded(name, |r| matches!(r.op, Op::Rotate(a, _) if a == angle));
843    }
844
845    /// Assert that an image was blurred.
846    pub fn assert_blurred(name: &str) {
847        Self::assert_recorded(name, |r| matches!(r.op, Op::Blur(_)));
848    }
849
850    /// Assert that an image was converted to grayscale.
851    pub fn assert_grayscale(name: &str) {
852        Self::assert_recorded(name, |r| matches!(r.op, Op::Grayscale));
853    }
854
855    /// Assert that an image was sharpened.
856    pub fn assert_sharpened(name: &str) {
857        Self::assert_recorded(name, |r| matches!(r.op, Op::Sharpen(_)));
858    }
859
860    /// Assert that an image was auto-oriented.
861    pub fn assert_oriented(name: &str) {
862        Self::assert_recorded(name, |r| matches!(r.op, Op::Orient));
863    }
864
865    /// Assert that an image was converted to the given output format.
866    pub fn assert_converted_to(name: &str, format: OutputFormat) {
867        Self::assert_recorded(name, |r| r.format == Some(format));
868    }
869
870    /// Assert that an image was stored to the given path.
871    pub fn assert_stored(name: &str, path: &str) {
872        Self::assert_recorded(name, |r| r.stored_to.as_deref() == Some(path));
873    }
874
875    /// Assert that an image was never stored.
876    pub fn assert_not_stored(name: &str) {
877        let state = fake_state().lock().unwrap();
878        let records = state.as_ref().expect("Image is not faked");
879        assert!(
880            !records
881                .iter()
882                .any(|r| { r.name == name && r.stored_to.is_some() }),
883            "Expected image `{name}` to NOT be stored, but it was."
884        );
885    }
886
887    fn assert_recorded(name: &str, predicate: impl Fn(&RecordedOp) -> bool) {
888        let state = fake_state().lock().unwrap();
889        let records = state.as_ref().expect("Image is not faked");
890        assert!(
891            records.iter().any(|r| r.name == name && predicate(r)),
892            "Expected a matching image operation for `{name}`.\nRecorded: {records:#?}"
893        );
894    }
895}
896
897fn record_fake(instance: &ImageInstance) {
898    let mut state = fake_state().lock().unwrap();
899    let Some(records) = state.as_mut() else {
900        return;
901    };
902    let name = instance
903        .source_name
904        .clone()
905        .unwrap_or_else(|| "image".to_string());
906    if let Some(op) = instance.ops.last().cloned() {
907        records.push(RecordedOp {
908            name: name.clone(),
909            op,
910            format: None,
911            quality: None,
912            stored_to: None,
913        });
914        if let Some(format) = instance.format {
915            records.push(RecordedOp {
916                name,
917                op: Op::Grayscale,
918                format: Some(format),
919                quality: None,
920                stored_to: None,
921            });
922        }
923    } else if let Some(format) = instance.format {
924        records.push(RecordedOp {
925            name,
926            op: Op::Grayscale,
927            format: Some(format),
928            quality: None,
929            stored_to: None,
930        });
931    }
932}
933
934// ============================================================================
935// TESTS
936// ============================================================================
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use std::io::Write;
942
943    fn solid_png(width: u32, height: u32, color: [u8; 3]) -> Vec<u8> {
944        let img = image::RgbImage::from_pixel(width, height, image::Rgb(color));
945        let mut buf = Cursor::new(Vec::new());
946        img.write_to(&mut buf, ImageFormat::Png).unwrap();
947        buf.into_inner()
948    }
949
950    fn temp_png_path(name: &str) -> std::path::PathBuf {
951        let dir = std::env::temp_dir().join(format!("larastvel_img_{}", uuid::Uuid::new_v4()));
952        std::fs::create_dir_all(&dir).unwrap();
953        let path = dir.join(name);
954        let mut file = std::fs::File::create(&path).unwrap();
955        file.write_all(&solid_png(200, 100, [255, 0, 0])).unwrap();
956        path
957    }
958
959    #[test]
960    fn from_bytes_and_dimensions() {
961        let img = Image::from_bytes(&solid_png(200, 100, [255, 0, 0])).unwrap();
962        assert_eq!(img.dimensions().unwrap(), (200, 100));
963        assert_eq!(img.width().unwrap(), 200);
964        assert_eq!(img.height().unwrap(), 100);
965        assert_eq!(img.mime_type().unwrap(), "image/png");
966        assert_eq!(img.extension(), "png");
967    }
968
969    #[test]
970    fn from_base64_roundtrip() {
971        let b64 = base64::engine::general_purpose::STANDARD.encode(solid_png(10, 10, [0, 255, 0]));
972        let img = Image::from_base64(&b64).unwrap();
973        assert_eq!(img.dimensions().unwrap(), (10, 10));
974        assert!(Image::from_base64("not base64!").is_err());
975    }
976
977    #[test]
978    fn from_path_reads_file() {
979        let path = temp_png_path("in.png");
980        let img = Image::from_path(&path.to_string_lossy()).unwrap();
981        assert_eq!(img.dimensions().unwrap(), (200, 100));
982        std::fs::remove_dir_all(path.parent().unwrap()).ok();
983    }
984
985    #[test]
986    fn resize_preserves_aspect_ratio() {
987        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
988        let resized = img.resize(Some(100), None).unwrap();
989        assert_eq!(resized.dimensions().unwrap(), (100, 50));
990        let resized = img.resize(None, Some(50)).unwrap();
991        assert_eq!(resized.dimensions().unwrap(), (100, 50));
992        let resized = img.resize(Some(60), Some(40)).unwrap();
993        assert_eq!(resized.dimensions().unwrap(), (60, 30));
994        assert!(img.resize(None, None).is_err());
995    }
996
997    #[test]
998    fn scale_never_upscales() {
999        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1000        let scaled = img.scale(Some(400), None).unwrap();
1001        assert_eq!(scaled.dimensions().unwrap(), (200, 100));
1002        let scaled = img.scale(Some(100), None).unwrap();
1003        assert_eq!(scaled.dimensions().unwrap(), (100, 50));
1004    }
1005
1006    #[test]
1007    fn cover_crops_to_dimensions() {
1008        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1009        let covered = img.cover(100, 100);
1010        assert_eq!(covered.dimensions().unwrap(), (100, 100));
1011        let covered = img.cover(150, 50);
1012        assert_eq!(covered.dimensions().unwrap(), (150, 50));
1013    }
1014
1015    #[test]
1016    fn contain_fits_within_dimensions() {
1017        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1018        let contained = img.contain(100, 100, None);
1019        assert_eq!(contained.dimensions().unwrap(), (100, 100));
1020        let contained = img.contain(100, 100, Some("#ffffff"));
1021        assert_eq!(contained.dimensions().unwrap(), (100, 100));
1022    }
1023
1024    #[test]
1025    fn crop_at_position() {
1026        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1027        let cropped = img.crop(50, 50, 10, 10);
1028        assert_eq!(cropped.dimensions().unwrap(), (50, 50));
1029        let cropped = img.crop(300, 200, 0, 0);
1030        assert_eq!(cropped.dimensions().unwrap(), (200, 100));
1031    }
1032
1033    #[test]
1034    fn rotate_quadrants_exact() {
1035        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1036        let rotated = img.rotate(90.0, None);
1037        assert_eq!(rotated.dimensions().unwrap(), (100, 200));
1038        let rotated = img.rotate(180.0, None);
1039        assert_eq!(rotated.dimensions().unwrap(), (200, 100));
1040        let rotated = img.rotate(270.0, None);
1041        assert_eq!(rotated.dimensions().unwrap(), (100, 200));
1042    }
1043
1044    #[test]
1045    fn grayscale_and_flips_change_pixels() {
1046        let img = Image::from_bytes(&solid_png(10, 10, [255, 0, 0])).unwrap();
1047        let gray = img.grayscale();
1048        assert_eq!(gray.dominant_color().unwrap(), "#363636");
1049        let flipped = img.flip_horizontally().flip_vertically();
1050        assert_eq!(flipped.dimensions().unwrap(), (10, 10));
1051    }
1052
1053    #[test]
1054    fn encode_conversions_and_quality() {
1055        let img = Image::from_bytes(&solid_png(10, 10, [255, 0, 0])).unwrap();
1056        let jpg = img.to_jpg();
1057        assert_eq!(jpg.mime_type().unwrap(), "image/jpeg");
1058        assert_eq!(jpg.extension(), "jpg");
1059        let webp = img.to_webp().quality(80);
1060        assert_eq!(webp.mime_type().unwrap(), "image/webp");
1061        assert_eq!(webp.extension(), "webp");
1062        assert!(webp.to_bytes().unwrap().starts_with(b"RIFF"));
1063        let bmp = img.to_bmp();
1064        assert_eq!(bmp.mime_type().unwrap(), "image/bmp");
1065        assert_eq!(bmp.extension(), "bmp");
1066    }
1067
1068    #[test]
1069    fn to_base64_and_data_uri() {
1070        let img = Image::from_bytes(&solid_png(10, 10, [255, 0, 0])).unwrap();
1071        let b64 = img.to_base64().unwrap();
1072        assert!(base64::engine::general_purpose::STANDARD
1073            .decode(&b64)
1074            .is_ok());
1075        let uri = img.to_data_uri().unwrap();
1076        assert!(uri.starts_with("data:image/png;base64,"));
1077    }
1078
1079    #[test]
1080    fn dominant_color_is_average() {
1081        let img = Image::from_bytes(&solid_png(10, 10, [0, 128, 255])).unwrap();
1082        assert_eq!(img.dominant_color().unwrap(), "#0080ff");
1083    }
1084
1085    #[test]
1086    fn save_writes_processed_image() {
1087        let path = temp_png_path("save-me.png");
1088        let dir = path.parent().unwrap();
1089        let out = dir.join("sub").join("out.webp");
1090        let img = Image::from_path(&path.to_string_lossy()).unwrap();
1091        img.cover(50, 50).to_webp().save(&out).unwrap();
1092        assert!(out.exists());
1093        let loaded = image::load_from_memory(&std::fs::read(&out).unwrap()).unwrap();
1094        assert_eq!((loaded.width(), loaded.height()), (50, 50));
1095        std::fs::remove_dir_all(dir).ok();
1096    }
1097
1098    #[test]
1099    fn immutable_pipeline_does_not_mutate_original() {
1100        let img = Image::from_bytes(&solid_png(200, 100, [0, 0, 255])).unwrap();
1101        let _processed = img.cover(50, 50);
1102        assert_eq!(img.dimensions().unwrap(), (200, 100));
1103        assert_eq!(
1104            img.to_bytes().unwrap().len(),
1105            solid_png(200, 100, [0, 0, 255]).len()
1106        );
1107    }
1108
1109    #[test]
1110    fn store_and_fake_record_operations() {
1111        let was_faked = Image::fake();
1112        // Uses `storage/app` under the crate working directory; use a unique
1113        // subdirectory and clean it up afterwards.
1114        let subdir = format!("_tests_{}", uuid::Uuid::new_v4());
1115        let img = Image::from_path(&temp_png_path("fake.png").to_string_lossy()).unwrap();
1116        let path = img
1117            .cover(100, 100)
1118            .to_webp()
1119            .store_as(&subdir, "out.webp")
1120            .unwrap();
1121        assert_eq!(path, format!("{subdir}/out.webp"));
1122        Image::assert_covered("fake.png", 100, 100);
1123        Image::assert_converted_to("fake.png", OutputFormat::Webp);
1124        Image::assert_stored("fake.png", &format!("{subdir}/out.webp"));
1125        Image::restore();
1126        assert!(!was_faked);
1127        assert!(!Image::is_faked());
1128        std::fs::remove_dir_all(crate::storage_path(Some("app")).join(&subdir)).ok();
1129    }
1130
1131    #[test]
1132    fn fake_records_crop_and_resize() {
1133        Image::fake();
1134        let img = Image::from_bytes(&solid_png(10, 10, [1, 2, 3])).unwrap();
1135        img.resize(Some(5), None).unwrap().crop(3, 3, 1, 1);
1136        Image::assert_resized("image", Some(5), None);
1137        Image::assert_cropped("image", 3, 3, 1, 1);
1138        Image::restore();
1139    }
1140
1141    #[test]
1142    fn assert_not_stored() {
1143        Image::fake();
1144        let img = Image::from_bytes(&solid_png(10, 10, [1, 2, 3])).unwrap();
1145        img.grayscale();
1146        Image::assert_not_stored("image");
1147        Image::restore();
1148    }
1149}