Skip to main content

use_image/
mime.rs

1use crate::format::ImageFormat;
2
3pub(crate) fn normalize_mime_value(mime: &str) -> Option<String> {
4    let value = mime.split(';').next()?.trim();
5
6    if value.is_empty() {
7        return None;
8    }
9
10    Some(value.to_ascii_lowercase())
11}
12
13/// Detects an image format from a MIME type string.
14#[must_use]
15pub fn detect_image_format_from_mime(mime: &str) -> ImageFormat {
16    let Some(normalized) = normalize_mime_value(mime) else {
17        return ImageFormat::Unknown;
18    };
19
20    match normalized.as_str() {
21        "image/png" => ImageFormat::Png,
22        "image/jpeg" | "image/jpg" | "image/pjpeg" => ImageFormat::Jpeg,
23        "image/webp" => ImageFormat::Webp,
24        "image/gif" => ImageFormat::Gif,
25        "image/svg+xml" | "image/svg" => ImageFormat::Svg,
26        "image/x-icon" | "image/vnd.microsoft.icon" => ImageFormat::Ico,
27        "image/bmp" | "image/x-ms-bmp" => ImageFormat::Bmp,
28        "image/tiff" | "image/tif" => ImageFormat::Tiff,
29        "image/avif" => ImageFormat::Avif,
30        _ => ImageFormat::Unknown,
31    }
32}
33
34/// Returns the canonical MIME type for a format.
35#[must_use]
36pub const fn image_mime_type(format: ImageFormat) -> Option<&'static str> {
37    match format {
38        ImageFormat::Png => Some("image/png"),
39        ImageFormat::Jpeg => Some("image/jpeg"),
40        ImageFormat::Webp => Some("image/webp"),
41        ImageFormat::Gif => Some("image/gif"),
42        ImageFormat::Svg => Some("image/svg+xml"),
43        ImageFormat::Ico => Some("image/x-icon"),
44        ImageFormat::Bmp => Some("image/bmp"),
45        ImageFormat::Tiff => Some("image/tiff"),
46        ImageFormat::Avif => Some("image/avif"),
47        ImageFormat::Unknown => None,
48    }
49}
50
51/// Returns true when the input is a known image MIME type.
52#[must_use]
53pub fn is_image_mime(mime: &str) -> bool {
54    detect_image_format_from_mime(mime) != ImageFormat::Unknown
55}