use std::path::Path;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
pub struct DataUri;
impl DataUri {
pub fn from_file(path: Option<&Path>) -> Option<String> {
let path = path?;
if !path.is_file() {
return None;
}
let contents = std::fs::read(path).ok()?;
Some(format!(
"data:{};base64,{}",
Self::mime(&contents),
STANDARD.encode(&contents)
))
}
fn mime(contents: &[u8]) -> &'static str {
match image::guess_format(contents) {
Ok(image::ImageFormat::Png) => "image/png",
Ok(image::ImageFormat::Jpeg) => "image/jpeg",
Ok(image::ImageFormat::WebP) => "image/webp",
Ok(image::ImageFormat::Gif) => "image/gif",
_ if contents.starts_with(b"<svg") || contents.starts_with(b"<?xml") => "image/svg+xml",
_ => "application/octet-stream",
}
}
}