Skip to main content

scyph_storage/thumbnail/
config.rs

1//! Thumbnail configuration and format metadata.
2
3use image::ImageFormat;
4
5use super::{generator::generate_thumbnail_with_format, key::derive_thumbnail_key_with_format};
6use crate::error::StorageError;
7
8/// Default square bounding dimension in pixels for thumbnails.
9pub const DEFAULT_THUMBNAIL_DIMENSION: u32 = 200;
10
11/// Default subdirectory name used when deriving thumbnail storage keys.
12pub const DEFAULT_THUMBNAIL_SUBFOLDER: &str = "thumbnails";
13
14/// Configuration builder for image thumbnail generation.
15///
16/// Encapsulates maximum bounding box constraints and the target output image encoding format.
17///
18/// # Examples
19///
20/// ```rust
21/// use image::ImageFormat;
22/// use scyph_storage::thumbnail::ThumbnailConfig;
23///
24/// let config = ThumbnailConfig::new(300, 300)
25///     .with_format(ImageFormat::Png);
26///
27/// assert_eq!(config.max_width, 300);
28/// assert_eq!(config.max_height, 300);
29/// assert_eq!(config.format, ImageFormat::Png);
30/// ```
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct ThumbnailConfig {
33    /// Maximum allowable width in pixels.
34    pub max_width: u32,
35    /// Maximum allowable height in pixels.
36    pub max_height: u32,
37    /// Target image encoding format for the generated thumbnail (default: JPEG).
38    pub format: ImageFormat,
39}
40
41impl Default for ThumbnailConfig {
42    fn default() -> Self {
43        Self {
44            max_width: DEFAULT_THUMBNAIL_DIMENSION,
45            max_height: DEFAULT_THUMBNAIL_DIMENSION,
46            format: ImageFormat::Jpeg,
47        }
48    }
49}
50
51impl ThumbnailConfig {
52    /// Creates a new [`ThumbnailConfig`] with custom maximum width and height bounds.
53    ///
54    /// By default, encodes output as JPEG.
55    ///
56    /// # Arguments
57    ///
58    /// * `max_width` - Maximum thumbnail width in pixels.
59    /// * `max_height` - Maximum thumbnail height in pixels.
60    pub const fn new(max_width: u32, max_height: u32) -> Self {
61        Self {
62            max_width,
63            max_height,
64            format: ImageFormat::Jpeg,
65        }
66    }
67
68    /// Configures the destination image encoding format (e.g. JPEG, PNG, WebP).
69    ///
70    /// # Arguments
71    ///
72    /// * `format` - Target [`ImageFormat`].
73    pub fn with_format(mut self, format: ImageFormat) -> Self {
74        self.format = format;
75        self
76    }
77
78    /// Generates a thumbnail buffer from the provided raw image bytes using this configuration.
79    ///
80    /// Preserves original aspect ratio while scaling down to fit within `(max_width, max_height)`.
81    ///
82    /// # Arguments
83    ///
84    /// * `data` - Raw bytes of the source image (cheaply shared if `Bytes`).
85    ///
86    /// # Errors
87    ///
88    /// Returns [`StorageError::ValidationError`] if image format is unsupported or bytes are corrupt,
89    /// or [`StorageError::Internal`] if re-encoding fails.
90    pub async fn generate(&self, data: impl Into<bytes::Bytes>) -> Result<Vec<u8>, StorageError> {
91        generate_thumbnail_with_format(data, self.max_width, self.max_height, self.format).await
92    }
93
94    /// Returns the canonical MIME content-type string for this configuration's target output format.
95    ///
96    /// # Examples
97    ///
98    /// ```rust
99    /// use image::ImageFormat;
100    /// use scyph_storage::thumbnail::ThumbnailConfig;
101    ///
102    /// let config = ThumbnailConfig::default().with_format(ImageFormat::WebP);
103    /// assert_eq!(config.content_type(), "image/webp");
104    /// ```
105    pub const fn content_type(&self) -> &'static str {
106        format_content_type(self.format)
107    }
108
109    /// Returns the canonical file extension (without leading dot) for this configuration's format.
110    pub const fn extension(&self) -> &'static str {
111        format_extension(self.format)
112    }
113
114    /// Derives the destination storage key for a thumbnail based on this configuration's format.
115    ///
116    /// Replaces the original extension with the target format extension and places the file in `subfolder`.
117    ///
118    /// # Examples
119    ///
120    /// ```rust
121    /// use image::ImageFormat;
122    /// use scyph_storage::thumbnail::ThumbnailConfig;
123    ///
124    /// let config = ThumbnailConfig::default().with_format(ImageFormat::WebP);
125    /// let key = config.derive_key("avatars/user.png", "thumbnails");
126    /// assert_eq!(key, "avatars/thumbnails/user.webp");
127    /// ```
128    pub fn derive_key(&self, original_key: &str, subfolder: &str) -> String {
129        derive_thumbnail_key_with_format(original_key, subfolder, self.format)
130    }
131}
132
133/// Returns the canonical MIME content-type string corresponding to an [`ImageFormat`].
134pub const fn format_content_type(format: ImageFormat) -> &'static str {
135    match format {
136        ImageFormat::Jpeg => "image/jpeg",
137        ImageFormat::Png => "image/png",
138        ImageFormat::WebP => "image/webp",
139        ImageFormat::Gif => "image/gif",
140        ImageFormat::Bmp => "image/bmp",
141        ImageFormat::Ico => "image/x-icon",
142        ImageFormat::Tiff => "image/tiff",
143        _ => "application/octet-stream",
144    }
145}
146
147/// Returns the primary file extension (without leading dot) corresponding to an [`ImageFormat`].
148pub const fn format_extension(format: ImageFormat) -> &'static str {
149    match format {
150        ImageFormat::Jpeg => "jpg",
151        ImageFormat::Png => "png",
152        ImageFormat::WebP => "webp",
153        ImageFormat::Gif => "gif",
154        ImageFormat::Bmp => "bmp",
155        ImageFormat::Ico => "ico",
156        ImageFormat::Tiff => "tiff",
157        _ => "bin",
158    }
159}