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};
#[derive(Clone)]
pub struct Layer {
pub lines: Vec<String>,
pub size: i32,
pub x: i32,
pub dy: i32,
pub baseline: i32,
pub font: Arc<TextFitter>,
pub color: String,
pub align: Align,
pub highlights: Vec<[i32; 4]>,
pub highlight_color: String,
}
pub struct ImageComposer;
impl ImageComposer {
pub const EXTENSIONS: [&'static str; 4] = ["png", "jpg", "jpeg", "webp"];
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()))
}
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(());
}
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(())
}
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()
))
})
}
}