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::fs::File;
use std::io::BufWriter;
use std::path::Path;

use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::codecs::webp::WebPEncoder;
use image::{ExtendedColorType, ImageEncoder, RgbImage, RgbaImage};

use crate::config::Format;
use crate::exceptions::RenderFailed;

/// Writes a rendered card in the requested file format.
pub struct Raster;

impl Raster {
    /// Normalises an extension or a format name, or `None` if it is not supported. `jpeg` is `jpg`.
    pub fn normalise(format: Option<&str>) -> Option<Format> {
        match format?.trim().to_lowercase().as_str() {
            "png" => Some(Format::Png),
            "jpg" | "jpeg" => Some(Format::Jpg),
            "webp" => Some(Format::Webp),
            _ => None,
        }
    }

    /// Writes `image` to `target` as `format`. A JPEG is flattened onto white, because it has no alpha.
    ///
    /// # Errors
    ///
    /// Fails when the file cannot be created or encoded.
    pub fn write(image: &RgbaImage, target: &Path, format: Format, quality: u8) -> Result<(), RenderFailed> {
        let failed = |error: &dyn std::fmt::Display| {
            RenderFailed::new(format!(
                "Laracards: could not write {} to {}: {error}",
                format.extension(),
                target.display()
            ))
        };
        let writer = BufWriter::new(File::create(target).map_err(|error| failed(&error))?);
        let (width, height) = image.dimensions();

        match format {
            Format::Png => PngEncoder::new(writer)
                .write_image(image.as_raw(), width, height, ExtendedColorType::Rgba8)
                .map_err(|error| failed(&error)),
            Format::Webp => WebPEncoder::new_lossless(writer)
                .write_image(image.as_raw(), width, height, ExtendedColorType::Rgba8)
                .map_err(|error| failed(&error)),
            Format::Jpg => JpegEncoder::new_with_quality(writer, quality.clamp(1, 100))
                .write_image(Self::flatten(image).as_raw(), width, height, ExtendedColorType::Rgb8)
                .map_err(|error| failed(&error)),
        }
    }

    /// A JPEG has no alpha, so anything transparent has to land on something. White is the least
    /// surprising choice for a card.
    fn flatten(image: &RgbaImage) -> RgbImage {
        let mut flat = RgbImage::new(image.width(), image.height());

        for (source, target) in image.pixels().zip(flat.pixels_mut()) {
            let alpha = f32::from(source[3]) / 255.0;

            for channel in 0..3 {
                target[channel] = (f32::from(source[channel]) * alpha + 255.0 * (1.0 - alpha)).round() as u8;
            }
        }

        flat
    }
}