ragit_pdl/
image.rs

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
use crate::error::Error;
use regex::Regex;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ImageType {
    Jpeg,
    Png,
    Gif,
    Webp,
}

impl ImageType {
    // for anthropic api
    pub fn get_media_type(&self) -> &str {
        match self {
            ImageType::Jpeg => "image/jpeg",
            ImageType::Png => "image/png",
            ImageType::Gif => "image/gif",
            ImageType::Webp => "image/webp",
        }
    }

    pub fn from_media_type(s: &str) -> Result<Self, Error> {
        match s.to_ascii_lowercase() {
            s if s == "image/jpeg" || s == "image/jpg" => Ok(ImageType::Jpeg),
            s if s == "image/png" => Ok(ImageType::Png),
            s if s == "image/gif" => Ok(ImageType::Gif),
            s if s == "image/webp" => Ok(ImageType::Webp),
            _ => Err(Error::InvalidImageType(s.to_string())),
        }
    }

    pub fn from_extension(ext: &str) -> Result<Self, Error> {
        match ext.to_ascii_lowercase() {
            ext if ext == "png" => Ok(ImageType::Png),
            ext if ext == "jpeg" || ext == "jpg" => Ok(ImageType::Jpeg),
            ext if ext == "gif" => Ok(ImageType::Gif),
            ext if ext == "webp" => Ok(ImageType::Webp),
            _ => Err(Error::InvalidImageType(ext.to_string())),
        }
    }

    pub fn infer_from_path(path: &str) -> Result<Self, Error> {
        let ext_re = Regex::new(r".+\.([^.]+)$").unwrap();

        if let Some(ext) = ext_re.captures(path) {
            ImageType::from_extension(ext.get(1).unwrap().as_str())
        }

        else {
            Err(Error::InvalidImageType(path.to_string()))
        }
    }

    pub fn to_extension(&self) -> &str {
        match self {
            ImageType::Jpeg => "jpg",
            ImageType::Png => "png",
            ImageType::Gif => "gif",
            ImageType::Webp => "webp",
        }
    }
}

impl From<ImageType> for image::ImageFormat {
    fn from(image_type: ImageType) -> Self {
        match image_type {
            ImageType::Jpeg => image::ImageFormat::Jpeg,
            ImageType::Png => image::ImageFormat::Png,
            ImageType::Gif => image::ImageFormat::Gif,
            ImageType::Webp => image::ImageFormat::WebP,
        }
    }
}