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 std::sync::Arc;

use image::RgbaImage;
use image::imageops::{self, FilterType};
use resvg::tiny_skia::{FillRule, Paint, Pixmap, Rect, Transform};

use crate::config::Align;
use crate::exceptions::RenderFailed;
use crate::support::{Color, TextFitter};

/// A block of text laid out and ready to draw: the lines, where they sit and how they look.
#[derive(Clone)]
pub struct Layer {
    /// The wrapped lines.
    pub lines: Vec<String>,
    /// The font size, in pixels.
    pub size: i32,
    /// Where the lines are anchored horizontally.
    pub x: i32,
    /// The distance between two baselines.
    pub dy: i32,
    /// The baseline of the first line.
    pub baseline: i32,
    /// The face to draw with.
    pub font: Arc<TextFitter>,
    /// The colour of the text.
    pub color: String,
    /// How the lines are anchored on `x`.
    pub align: Align,
    /// The x, y, width and height of the bar behind each line.
    pub highlights: Vec<[i32; 4]>,
    /// The colour of the bars.
    pub highlight_color: String,
}

/// Draws a card straight onto a raster template, for templates that are an image instead of an SVG.
///
/// There is no SVG to say where the text goes, so every layer arrives already laid out: lines, size,
/// position and baseline come from the same fit rules the SVG path uses, plus the colour and alignment
/// an SVG would carry itself. The PHP package draws with GD; here the outlines of the face are filled
/// with `tiny-skia`, the rasteriser `resvg` uses.
pub struct ImageComposer;

impl ImageComposer {
    /// The extensions of a raster template.
    pub const EXTENSIONS: [&'static str; 4] = ["png", "jpg", "jpeg", "webp"];

    /// Whether a template is an image rather than an SVG.
    pub fn handles(template_path: &Path) -> bool {
        template_path
            .extension()
            .and_then(|extension| extension.to_str())
            .is_some_and(|extension| Self::EXTENSIONS.contains(&extension.to_lowercase().as_str()))
    }

    /// Draws the layers onto the template, with the card background under it.
    ///
    /// The background goes under the template, so a template with transparent areas works as an overlay
    /// on a photo, the same way the SVG path layers `__BACKGROUND_URI__` beneath the design.
    ///
    /// # Errors
    ///
    /// Fails when an image cannot be read, or a colour is not a colour.
    pub fn compose(
        &self,
        template_path: &Path,
        width: u32,
        height: u32,
        background: Option<&Path>,
        layers: &[Layer],
    ) -> Result<RgbaImage, RenderFailed> {
        let mut canvas = RgbaImage::new(width, height);

        if let Some(background) = background {
            Self::cover(&mut canvas, &Self::open(background)?);
        }

        Self::cover(&mut canvas, &Self::open(template_path)?);

        let mut pixmap =
            Pixmap::new(width, height).ok_or_else(|| RenderFailed::new("Laracards: the card has no size."))?;

        for layer in layers {
            Self::text(&mut pixmap, layer).map_err(|error| RenderFailed::new(error.to_string()))?;
        }

        let ink = RgbaImage::from_fn(width, height, |x, y| {
            let color = pixmap.pixel(x, y).map(|pixel| pixel.demultiply());

            color.map_or(image::Rgba([0, 0, 0, 0]), |c| {
                image::Rgba([c.red(), c.green(), c.blue(), c.alpha()])
            })
        });

        imageops::overlay(&mut canvas, &ink, 0, 0);

        Ok(canvas)
    }

    fn text(pixmap: &mut Pixmap, layer: &Layer) -> laravel::Result<()> {
        if layer.lines.is_empty() {
            return Ok(());
        }

        // The boxes go first, so every line's text lands on top of its own box.
        if !layer.highlights.is_empty() {
            let [r, g, b, a] = Color::parse(&layer.highlight_color)?;
            let mut paint = Paint::default();

            paint.set_color_rgba8(r, g, b, a);
            paint.anti_alias = false;

            for [x, y, width, height] in &layer.highlights {
                if let Some(rect) = Rect::from_xywh(*x as f32, *y as f32, *width as f32, *height as f32) {
                    pixmap.fill_rect(rect, &paint, Transform::identity(), None);
                }
            }
        }

        let [r, g, b, a] = Color::parse(&layer.color)?;
        let mut paint = Paint::default();

        paint.set_color_rgba8(r, g, b, a);
        paint.anti_alias = true;

        for (index, line) in layer.lines.iter().enumerate() {
            let mut x = layer.x;

            if layer.align != Align::Left {
                let width = layer.font.width(line, layer.size);

                x -= match layer.align {
                    Align::Center => (f64::from(width) / 2.0).round() as i32,
                    _ => width,
                };
            }

            if let Some(outline) = layer.font.outline(line, layer.size) {
                let baseline = layer.baseline + index as i32 * layer.dy;

                pixmap.fill_path(
                    &outline,
                    &paint,
                    FillRule::Winding,
                    Transform::from_translate(x as f32, baseline as f32),
                    None,
                );
            }
        }

        Ok(())
    }

    /// Scales `source` to fill the canvas, cropping the overflow from the centre.
    fn cover(canvas: &mut RgbaImage, source: &RgbaImage) {
        let (width, height) = canvas.dimensions();
        let (source_width, source_height) = source.dimensions();
        let scale = (f64::from(width) / f64::from(source_width)).max(f64::from(height) / f64::from(source_height));
        let crop_width = ((f64::from(width) / scale).round() as u32).clamp(1, source_width);
        let crop_height = ((f64::from(height) / scale).round() as u32).clamp(1, source_height);
        let left = (f64::from(source_width - crop_width) / 2.0).round() as u32;
        let top = (f64::from(source_height - crop_height) / 2.0).round() as u32;

        let cropped = imageops::crop_imm(source, left, top, crop_width, crop_height).to_image();

        if cropped.dimensions() == (width, height) {
            imageops::overlay(canvas, &cropped, 0, 0);
        } else {
            imageops::overlay(
                canvas,
                &imageops::resize(&cropped, width, height, FilterType::Lanczos3),
                0,
                0,
            );
        }
    }

    fn open(path: &Path) -> Result<RgbaImage, RenderFailed> {
        image::open(path).map(|image| image.to_rgba8()).map_err(|error| {
            RenderFailed::new(format!(
                "Laracards: could not read the image at {}: {error}",
                path.display()
            ))
        })
    }
}