master
Ray
Publish 0.5.0
9332b6e
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
//! SVG -> PNG through resvg, sized for chat (a fixed pixel width), with the system fonts loaded so labels render.
use anyhow::{anyhow, Context, Result};
use resvg::{tiny_skia, usvg};
pub fn svg_to_png(svg: &str, width_px: u32) -> Result<Vec<u8>> {
let mut opt = usvg::Options::default();
opt.fontdb_mut().load_system_fonts();
let tree = usvg::Tree::from_str(svg, &opt).context("parse SVG for PNG")?;
let size = tree.size();
let scale = width_px as f32 / size.width();
let height_px = (size.height() * scale).ceil().max(1.0) as u32;
let mut pixmap = tiny_skia::Pixmap::new(width_px, height_px).ok_or_else(|| anyhow!("PNG of {width_px}x{height_px} px"))?;
pixmap.fill(tiny_skia::Color::WHITE);
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
// Opaque on white. Boards are a few dozen flat colours plus anti-aliased edges, so a 256-colour palette of the
// most frequent colours (edges mapped to their nearest) keeps the look and roughly halves the file.
let rgb: Vec<[u8; 3]> = pixmap.data().chunks_exact(4).map(|p| [p[0], p[1], p[2]]).collect();
let mut counts: std::collections::HashMap<[u8; 3], u32> = std::collections::HashMap::new();
for c in &rgb { *counts.entry(*c).or_default() += 1; }
let mut by_freq: Vec<([u8; 3], u32)> = counts.into_iter().collect();
by_freq.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let palette: Vec<[u8; 3]> = by_freq.iter().take(256).map(|(c, _)| *c).collect();
let mut index_of: std::collections::HashMap<[u8; 3], u8> = palette.iter().enumerate().map(|(i, c)| (*c, i as u8)).collect();
let nearest = |c: [u8; 3]| -> u8 {
let d = |p: &[u8; 3]| (0..3).map(|k| { let v = p[k] as i32 - c[k] as i32; v * v }).sum::<i32>();
(0..palette.len()).min_by_key(|&i| d(&palette[i])).unwrap_or(0) as u8
};
let indices: Vec<u8> = rgb.iter().map(|c| match index_of.get(c) { Some(i) => *i, None => { let i = nearest(*c); index_of.insert(*c, i); i } }).collect();
let mut out = Vec::new();
{
let mut enc = png::Encoder::new(&mut out, width_px, height_px);
enc.set_color(png::ColorType::Indexed);
enc.set_depth(png::BitDepth::Eight);
enc.set_palette(palette.iter().flatten().copied().collect::<Vec<u8>>());
enc.set_compression(png::Compression::Best);
enc.set_adaptive_filter(png::AdaptiveFilterType::NonAdaptive);
enc.set_filter(png::FilterType::NoFilter);
let mut w = enc.write_header().context("PNG header")?;
w.write_image_data(&indices).context("encode PNG")?;
}
Ok(out)
}
#[cfg(test)]
mod tests {
#[test]
fn png_is_indexed_at_the_requested_width() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 5" width="400" height="200"><rect width="10" height="5" fill="white"/><circle cx="5" cy="2.5" r="2" fill="#c33"/><text x="5" y="2.5" font-size="1" fill="white">MC1</text></svg>"##;
let png = super::svg_to_png(svg, 1000).unwrap();
assert_eq!(&png[1..4], b"PNG");
let be = |i: usize| u32::from_be_bytes(png[i..i + 4].try_into().unwrap());
assert_eq!((be(16), be(20)), (1000, 500));
assert_eq!(png[25], 3, "colour type 3: palette");
}
}