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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! The image manager: Intervention Image's `ImageManager` and the driver's decoders.

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

use base64::Engine;
use image::{AnimationDecoder, ImageDecoder, ImageFormat, RgbaImage};

use crate::config::{DriverConfig, current};
use crate::encoders::EncodedImage;
use crate::error::{ImageError, Result};
use crate::exif::Exif;
use crate::format::MediaType;
use crate::image::{Frame, Image, Origin};

/// What [`ImageManager::decode`] accepts: PHP's `decode(mixed $source)`.
///
/// Strings are tried as a data URI, then Base64, then a file path, in PHP's order. Byte slices
/// and vectors are binary image data, [`Path`]s are paths, and an uploaded file is decoded from
/// its temporary file.
#[derive(Debug, Clone)]
pub enum Source {
    /// A string: a data URI, Base64 or a path.
    Text(String),
    /// A file path.
    Path(PathBuf),
    /// Binary image data.
    Binary(Vec<u8>),
    /// An image, which is cloned.
    Image(Box<Image>),
}

impl From<&str> for Source {
    fn from(value: &str) -> Self {
        Source::Text(value.to_owned())
    }
}

impl From<String> for Source {
    fn from(value: String) -> Self {
        Source::Text(value)
    }
}

impl From<&String> for Source {
    fn from(value: &String) -> Self {
        Source::Text(value.clone())
    }
}

impl From<&Path> for Source {
    fn from(value: &Path) -> Self {
        Source::Path(value.to_path_buf())
    }
}

impl From<PathBuf> for Source {
    fn from(value: PathBuf) -> Self {
        Source::Path(value)
    }
}

impl From<&PathBuf> for Source {
    fn from(value: &PathBuf) -> Self {
        Source::Path(value.clone())
    }
}

impl From<Vec<u8>> for Source {
    fn from(value: Vec<u8>) -> Self {
        Source::Binary(value)
    }
}

impl From<&Vec<u8>> for Source {
    fn from(value: &Vec<u8>) -> Self {
        Source::Binary(value.clone())
    }
}

impl From<&[u8]> for Source {
    fn from(value: &[u8]) -> Self {
        Source::Binary(value.to_vec())
    }
}

impl<const N: usize> From<&[u8; N]> for Source {
    fn from(value: &[u8; N]) -> Self {
        Source::Binary(value.to_vec())
    }
}

impl From<laravel::storage::Bytes> for Source {
    fn from(value: laravel::storage::Bytes) -> Self {
        Source::Binary(value.to_vec())
    }
}

impl From<&laravel::http::UploadedFile> for Source {
    fn from(value: &laravel::http::UploadedFile) -> Self {
        Source::Path(value.path().to_path_buf())
    }
}

impl From<laravel::http::UploadedFile> for Source {
    fn from(value: laravel::http::UploadedFile) -> Self {
        Source::Path(value.path().to_path_buf())
    }
}

impl From<Image> for Source {
    fn from(value: Image) -> Self {
        Source::Image(Box::new(value))
    }
}

impl From<&Image> for Source {
    fn from(value: &Image) -> Self {
        Source::Image(Box::new(value.clone()))
    }
}

impl From<EncodedImage> for Source {
    fn from(value: EncodedImage) -> Self {
        Source::Binary(value.into_bytes())
    }
}

impl From<&EncodedImage> for Source {
    fn from(value: &EncodedImage) -> Self {
        Source::Binary(value.as_bytes().to_vec())
    }
}

/// The image manager: Intervention Image's `ImageManager`, bound in the container by the
/// [`ImageServiceProvider`](crate::ImageServiceProvider) with the application's configuration
/// (PHP's `ImageManagerInterface` injection). The [`Image`] facade functions use it too.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImageManager {
    config: DriverConfig,
}

impl ImageManager {
    /// A manager with the given driver options: `new ImageManager($driver, ...$options)`.
    pub fn new(config: DriverConfig) -> Self {
        Self { config }
    }

    /// `ImageManager::usingDriver()` with the defaults: the only driver is the pure-Rust one.
    pub fn using_driver() -> Self {
        Self::default()
    }

    /// The manager of the running application's [`ImageConfig`](crate::ImageConfig), or the
    /// defaults outside an application.
    pub fn configured() -> Self {
        Self::new(current().options())
    }

    /// The driver options: `$manager->driver()->config()`.
    pub fn config(&self) -> &DriverConfig {
        &self.config
    }

    /// `createImage($width, $height)`: a new, fully transparent image.
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] when a side is smaller than 1.
    pub fn create_image(&self, width: u32, height: u32) -> Result<Image> {
        if width < 1 || height < 1 {
            return Err(ImageError::InvalidArgument(
                "Invalid image size. Must be int<1, max>".to_owned(),
            ));
        }
        let buffer = RgbaImage::from_pixel(width, height, image::Rgba([255, 255, 255, 0]));
        Ok(Image::from_frames(
            vec![Frame {
                buffer,
                delay: Duration::ZERO,
            }],
            self.config.clone(),
        ))
    }

    /// `decode($source)`: decode any [`Source`].
    ///
    /// # Errors
    ///
    /// [`ImageError::InvalidArgument`] for an empty string, the errors of the decoder chosen for
    /// the source otherwise.
    pub fn decode(&self, source: impl Into<Source>) -> Result<Image> {
        match source.into() {
            Source::Image(image) => Ok(*image),
            Source::Binary(bytes) => self.decode_binary(bytes),
            Source::Path(path) => self.decode_path(path),
            Source::Text(text) => {
                if text.is_empty() {
                    return Err(ImageError::InvalidArgument(
                        "Unable to decode from empty string".to_owned(),
                    ));
                }
                if is_data_uri(&text) {
                    return self.decode_data_uri(&text);
                }
                if let Some(bytes) = base64_image(&text) {
                    return self.decode_binary(bytes);
                }
                self.decode_path(text)
            }
        }
    }

    /// `decodePath($path)`.
    ///
    /// # Errors
    ///
    /// [`ImageError::DirectoryNotFound`], [`ImageError::FileNotFound`] or
    /// [`ImageError::FileNotReadable`] for a bad path, [`ImageError::Decoder`] when the file isn't
    /// a supported image.
    pub fn decode_path(&self, path: impl AsRef<Path>) -> Result<Image> {
        let path = path.as_ref();
        let display = path.display();
        let directory = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .unwrap_or(Path::new("."));
        if !directory.is_dir() {
            return Err(ImageError::DirectoryNotFound(format!(
                "Directory \"{}\" not found",
                directory.display()
            )));
        }
        if !path.is_file() {
            return Err(ImageError::FileNotFound(format!("File \"{display}\" not found")));
        }
        let bytes = std::fs::read(path)
            .map_err(|error| ImageError::FileNotReadable(format!("File \"{display}\" is not readable: {error}")))?;
        let mut image = decode_bytes(&bytes, &self.config)?;
        image.origin = Origin::new(media_type_of(&bytes)?, Some(path.to_path_buf()));
        Ok(image)
    }

    /// `decodeBinary($binary)`.
    ///
    /// # Errors
    ///
    /// [`ImageError::Decoder`] when the data isn't a supported image.
    pub fn decode_binary(&self, binary: impl AsRef<[u8]>) -> Result<Image> {
        decode_bytes(binary.as_ref(), &self.config)
    }

    /// `decodeBase64($base64)`.
    ///
    /// # Errors
    ///
    /// [`ImageError::Decoder`] for invalid Base64 or data that isn't a supported image.
    pub fn decode_base64(&self, base64: &str) -> Result<Image> {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(base64.trim())
            .map_err(|_| ImageError::Decoder("Input is not Base64-encoded data".to_owned()))?;
        self.decode_binary(bytes)
    }

    /// `decodeDataUri($dataUri)`: `data:image/png;base64,...` or a URL-encoded data URI.
    ///
    /// # Errors
    ///
    /// [`ImageError::Decoder`] for a malformed data URI or data that isn't a supported image.
    pub fn decode_data_uri(&self, data_uri: &str) -> Result<Image> {
        let malformed = || ImageError::Decoder("Input is not a valid data URI".to_owned());
        let rest = data_uri.strip_prefix("data:").ok_or_else(malformed)?;
        let (meta, data) = rest.split_once(',').ok_or_else(malformed)?;
        if meta.split(';').any(|part| part.eq_ignore_ascii_case("base64")) {
            return self.decode_base64(data);
        }
        self.decode_binary(percent_decode(data))
    }

    /// `decodeSplFileInfo($file)`: decode an uploaded file from its temporary file.
    ///
    /// # Errors
    ///
    /// The errors of [`decode_path`](Self::decode_path).
    pub fn decode_uploaded_file(&self, file: &laravel::http::UploadedFile) -> Result<Image> {
        self.decode_path(file.path())
    }
}

fn is_data_uri(text: &str) -> bool {
    text.starts_with("data:") && text.contains(',')
}

fn base64_image(text: &str) -> Option<Vec<u8>> {
    if text.len() < 8
        || !text
            .trim()
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"+/=\r\n".contains(&b))
    {
        return None;
    }
    let bytes = base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()?;
    image::guess_format(&bytes).is_ok().then_some(bytes)
}

fn percent_decode(data: &str) -> Vec<u8> {
    let bytes = data.as_bytes();
    let mut decoded = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3])
            && let Ok(byte) = u8::from_str_radix(hex, 16)
        {
            decoded.push(byte);
            i += 3;
            continue;
        }
        decoded.push(bytes[i]);
        i += 1;
    }
    decoded
}

pub(crate) fn media_type_of(bytes: &[u8]) -> Result<MediaType> {
    let format = image::guess_format(bytes).map_err(|_| ImageError::Decoder("Unable to decode input".to_owned()))?;
    Ok(match format {
        ImageFormat::Jpeg => MediaType::ImageJpeg,
        ImageFormat::Png => MediaType::ImagePng,
        ImageFormat::Gif => MediaType::ImageGif,
        ImageFormat::WebP => MediaType::ImageWebp,
        ImageFormat::Avif => MediaType::ImageAvif,
        ImageFormat::Bmp => MediaType::ImageBmp,
        ImageFormat::Tiff => MediaType::ImageTiff,
        ImageFormat::Ico => MediaType::ImageXIcon,
        other => {
            return Err(ImageError::NotSupported(format!(
                "Unable to decode images of the format {other:?}"
            )));
        }
    })
}

/// The most memory the frames of a decoded animation may take together: the `image` crate's
/// default allocation limit, which also applies to every single image it decodes.
const MAX_DECODED_BYTES: u64 = 512 * 1024 * 1024;

/// Decode image data with the driver options: frames, Exif, auto-orientation.
pub(crate) fn decode_bytes(bytes: &[u8], config: &DriverConfig) -> Result<Image> {
    let media_type = media_type_of(bytes)?;
    let decode_error = |error: image::ImageError| match error {
        image::ImageError::Unsupported(error) => ImageError::NotSupported(format!("Unable to decode input: {error}")),
        error => ImageError::Decoder(format!("Unable to decode input: {error}")),
    };

    let mut loops = 0;
    let frames = if media_type == MediaType::ImageGif && config.decode_animation {
        // The GIF decoder has no limits of its own, unlike the other decoders, so a small file
        // with a huge canvas or many frames could take all the memory: it gets the same limits,
        // and its frames together may take no more than one image may.
        let mut decoder = image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).map_err(decode_error)?;
        decoder.set_limits(image::Limits::default()).map_err(decode_error)?;
        let mut frames = Vec::new();
        let mut total: u64 = 0;
        for frame in decoder.into_frames() {
            let frame = frame.map_err(decode_error)?;
            total = total.saturating_add(frame.buffer().len() as u64);
            if total > MAX_DECODED_BYTES {
                return Err(ImageError::Decoder(
                    "Unable to decode input: the animation's frames exceed the memory limit".to_owned(),
                ));
            }
            let (numerator, denominator) = frame.delay().numer_denom_ms();
            let delay = Duration::from_micros(u64::from(numerator) * 1000 / u64::from(denominator.max(1)));
            frames.push(Frame {
                buffer: frame.into_buffer(),
                delay,
            });
        }
        loops = gif_loops(bytes);
        frames
    } else {
        let format = image::guess_format(bytes).map_err(decode_error)?;
        let decoded = image::load_from_memory_with_format(bytes, format).map_err(decode_error)?;
        vec![Frame {
            buffer: decoded.to_rgba8(),
            delay: Duration::ZERO,
        }]
    };

    let mut image = Image::from_frames(frames, config.clone());
    image.loops = loops;
    image.origin = Origin::new(media_type, None);
    image.exif = Exif::read(bytes);
    if config.auto_orientation {
        image.orient();
    }
    Ok(image)
}

fn gif_loops(bytes: &[u8]) -> u16 {
    let mut options = gif::DecodeOptions::new();
    options.set_color_output(gif::ColorOutput::Indexed);
    let Ok(mut decoder) = options.read_info(Cursor::new(bytes)) else {
        return 0;
    };
    let _ = decoder.next_frame_info();
    match decoder.repeat() {
        gif::Repeat::Infinite => 0,
        gif::Repeat::Finite(count) => count,
    }
}