use anyhow::Result;
use base64::Engine;
use std::path::Path;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ImageData {
pub base64_data: String,
pub mime_type: String,
pub file_path: String,
pub size: u64,
}
pub fn detect_mime_type_from_content_type(content_type: &str) -> Option<String> {
let content_type = content_type.to_lowercase();
if content_type.starts_with("image/png") {
Some("image/png".to_string())
} else if content_type.starts_with("image/jpeg") || content_type.starts_with("image/jpg") {
Some("image/jpeg".to_string())
} else if content_type.starts_with("image/gif") {
Some("image/gif".to_string())
} else if content_type.starts_with("image/webp") {
Some("image/webp".to_string())
} else if content_type.starts_with("image/bmp") {
Some("image/bmp".to_string())
} else if content_type.starts_with("image/tiff") || content_type.starts_with("image/tif") {
Some("image/tiff".to_string())
} else if content_type.starts_with("image/svg") {
Some("image/svg+xml".to_string())
} else {
None
}
}
pub fn detect_mime_type_from_data(data: &[u8]) -> String {
if data.len() >= 2 && data[0] == 0xFF && data[1] == 0xD8 {
return "image/jpeg".to_string();
}
if data.len() < 8 {
return "image/png".to_string();
}
match &data[..8] {
[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] => "image/png".to_string(),
[0x47, 0x49, 0x46, 0x38, _, _, _, _] => {
if data.len() >= 12 && &data[8..12] == b"WEBP" {
"image/webp".to_string()
} else {
"image/gif".to_string()
}
}
[0x52, 0x49, 0x46, 0x46, _, _, _, _] => {
if data.len() >= 12 && &data[8..12] == b"WEBP" {
"image/webp".to_string()
} else {
"image/png".to_string()
}
}
[0x42, 0x4D, _, _] => "image/bmp".to_string(),
_ => "image/png".to_string(),
}
}
pub fn detect_mime_type_from_extension(path: &Path) -> Result<String> {
let extension = path
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
let mime_type = match extension.as_str() {
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"bmp" => "image/bmp",
"tiff" | "tif" => "image/tiff",
"svg" => "image/svg+xml",
_ => return Err(anyhow::anyhow!("Unsupported image format: {}", extension)),
};
Ok(mime_type.to_string())
}
pub fn has_supported_image_extension(path: &Path) -> bool {
let extension = path
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
const VALID_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tiff", "svg"];
VALID_EXTENSIONS.contains(&extension.as_str())
}
pub fn encode_to_base64(data: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(data)
}