Skip to main content

tauri_plugin_android_fs/api/models/
image.rs

1use serde::{Deserialize, Serialize};
2
3/// Image size
4/// 
5/// # Serialization
6/// Serialized by `serde` as the following TypeScript type:
7///
8/// ```ts
9/// type Size = {
10///     width: number,
11///     height: number,
12/// };
13/// ```
14#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Deserialize, Serialize)]
15pub struct Size {
16    pub width: u32,
17    pub height: u32
18}
19
20#[derive(Debug, Clone, Copy, PartialEq)]
21#[non_exhaustive]
22pub enum ImageFormat {
23
24    /// - Loss less
25    /// - Support transparency
26    Png,
27
28    /// - Lossy
29    /// - Unsupport transparency
30    Jpeg,
31
32    /// - Lossy (**Not loss less**)
33    /// - Support transparency
34    Webp,
35
36    /// - Lossy
37    /// - Unsupport transparency
38    JpegWith {
39
40        /// Range is `0.0 ~ 1.0`  
41        /// 0.0 means compress for the smallest size.  
42        /// 1.0 means compress for max visual quality.  
43        quality: f32
44    },
45
46    /// - Lossy
47    /// - Support transparency
48    WebpWith {
49        
50        /// Range is `0.0 ~ 1.0`  
51        /// 0.0 means compress for the smallest size.  
52        /// 1.0 means compress for max visual quality.  
53        quality: f32
54    }
55}
56
57#[allow(unused)]
58impl ImageFormat {
59
60    pub(crate) fn mime_type(&self) -> &'static str {
61        match self {
62            ImageFormat::Jpeg | ImageFormat::JpegWith { .. } => "image/jpeg",
63            ImageFormat::Webp | ImageFormat::WebpWith { .. } => "image/webp",
64            ImageFormat::Png => "image/png",
65        }
66    }
67
68    pub(crate) fn from_mime_type(mime_type: &str) -> Option<Self> {
69        match mime_type {
70            "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
71            "image/webp" => Some(Self::Webp),
72            "image/png" => Some(Self::Png),
73            _ => None,
74        }
75    }
76
77    pub(crate) fn from_name(name: &str) -> Option<Self> {
78        if name.eq_ignore_ascii_case("jpeg") || name.eq_ignore_ascii_case("jpg") {
79            Some(Self::Jpeg)
80        }
81        else if name.eq_ignore_ascii_case("webp") {
82            Some(Self::Webp)
83        }
84        else if name.eq_ignore_ascii_case("png") {
85            Some(Self::Png)
86        }
87        else {
88            None
89        }
90    }
91
92    pub(crate) fn to_quality_and_format_str(&self) -> (f32, &'static str) {
93        match self {
94            ImageFormat::Png => (1.0, "Png"),
95            ImageFormat::Jpeg => (0.75, "Jpeg"),
96            ImageFormat::Webp => (0.7, "Webp"),
97            ImageFormat::JpegWith { quality } => (*quality, "Jpeg"),
98            ImageFormat::WebpWith { quality } => (*quality, "Webp"),
99        }
100    }
101}