laracards 0.1.0

Editorial social cards and blog covers for Laravel Rust: SVG templates rendered natively, measured text fitting and pluggable backgrounds.
Documentation
use std::path::Path;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;

/// Embeds a local file into an SVG as a data URI.
pub struct DataUri;

impl DataUri {
    /// A `data:` URI for the file, or `None` when there is no such file.
    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",
        }
    }
}