Files
Pictor-public/crates/qr/src/svg.rs
T

106 lines
4.5 KiB
Rust

//! SVG output: one path of dark-module runs, a background rect, and the logo as a base64 PNG data URI.
use std::fmt::Write as _;
use std::io::Cursor;
use crate::encode::{Plate, prepare};
use crate::render::check_logo_size;
use crate::{Level, MAX_LOGO_BYTES, MAX_LOGO_PX, QrError, Style};
/// Renders `text` as SVG. The view box is in modules (quiet zone included); `width` and `height` are the same pixel
/// size [`crate::render_rgba`] would produce. Dark modules are one `<path>` of horizontal runs
/// (`M{x} {y}h{n}v1h-{n}z`). With `logo_png` (PNG bytes) the level is forced to H, the modules under the logo's
/// plate are left out, and the PNG is embedded unchanged as an `<image>` data URI.
pub fn render_svg(text: &str, level: Level, style: &Style, logo_png: Option<&[u8]>) -> Result<String, QrError> {
let logo_size = logo_png.map(logo_dimensions).transpose()?;
let (matrix, g, _) = prepare(text, level, style, logo_png.is_some())?;
let plate = logo_size.map(|(w, h)| Plate::new(&g, w, h));
let total = g.total_modules();
let size = g.size_px();
let mut svg = String::with_capacity(256 + (g.modules * g.modules) as usize * 4);
let _ = writeln!(
svg,
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" \
width=\"{size}\" height=\"{size}\" viewBox=\"0 0 {total} {total}\" shape-rendering=\"crispEdges\">\n"
);
if style.light[3] > 0 {
let _ = writeln!(svg, "<rect width=\"{total}\" height=\"{total}\"{}/>", fill(style.light));
}
let _ = write!(svg, "<path{} d=\"", fill(style.dark));
for my in 0..g.modules {
let mut mx = 0;
while mx < g.modules {
let on = |x: u32| matrix.is_dark(x, my) && !plate.as_ref().is_some_and(|p| p.contains(x, my));
if !on(mx) {
mx += 1;
continue;
}
let start = mx;
while mx < g.modules && on(mx) {
mx += 1;
}
let n = mx - start;
let _ = write!(svg, "M{} {}h{n}v1h-{n}z", g.quiet + start, g.quiet + my);
}
}
svg.push_str("\"/>\n");
if let (Some(png), Some(p)) = (logo_png, &plate) {
let s = f64::from(g.scale);
let q = f64::from(g.quiet);
let _ = writeln!(
svg,
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" \
xlink:href=\"data:image/png;base64,{}\"/>",
num(q + f64::from(p.logo_x) / s),
num(q + f64::from(p.logo_y) / s),
num(f64::from(p.logo_w) / s),
num(f64::from(p.logo_h) / s),
crate::base64::encode(png)
);
}
svg.push_str("</svg>\n");
Ok(svg)
}
/// Decodes the logo PNG (with caps on bytes, pixels and memory) to check it and read its size.
fn logo_dimensions(png: &[u8]) -> Result<(u32, u32), QrError> {
if png.len() > MAX_LOGO_BYTES {
return Err(QrError::Logo(format!(
"the file is {} MB; at most {} MB is allowed.",
png.len().div_ceil(1024 * 1024),
MAX_LOGO_BYTES / (1024 * 1024)
)));
}
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_LOGO_PX);
limits.max_image_height = Some(MAX_LOGO_PX);
limits.max_alloc = Some(u64::from(MAX_LOGO_PX) * u64::from(MAX_LOGO_PX) * 8);
reader.limits(limits);
let img = reader.decode().map_err(|e| match e {
image::ImageError::Limits(_) => {
QrError::Logo(format!("it is larger than {MAX_LOGO_PX} pixels on a side. Use a smaller image."))
}
_ => QrError::Logo("it is not a readable PNG image.".into()),
})?;
check_logo_size(img.width(), img.height())?;
Ok((img.width(), img.height()))
}
/// ` fill="#rrggbb"`, plus ` fill-opacity` when the colour is not opaque.
fn fill([r, g, b, a]: [u8; 4]) -> String {
let mut s = format!(" fill=\"#{r:02x}{g:02x}{b:02x}\"");
if a < 255 {
let _ = write!(s, " fill-opacity=\"{}\"", num(f64::from(a) / 255.0));
}
s
}
/// A number with at most three decimals and no trailing zeros.
fn num(v: f64) -> String {
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s.is_empty() || s == "-" { "0".into() } else { s.to_string() }
}