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

95 lines
3.8 KiB
Rust

//! Raster output: an RGBA image, and PNG bytes.
use image::{ImageEncoder, Rgba, RgbaImage, imageops};
use crate::encode::{Plate, prepare};
use crate::{Level, MAX_LOGO_PX, QrError, Style};
/// A rendered code.
#[derive(Debug, Clone)]
pub struct Rendered {
/// The code, `size_px` square, quiet zone included.
pub image: RgbaImage,
/// The error-correction level actually used: H whenever a logo was drawn, whatever was asked.
pub level_used: Level,
/// Modules across the code, quiet zone excluded (21 for version 1, up to 177).
pub modules: u32,
/// Pixels per module.
pub module_px: u32,
/// The real width and height in pixels: `(modules + 2 * quiet_zone) * module_px`, at most the asked size.
pub size_px: u32,
}
/// Renders `text` as an RGBA image. With a `logo` the level is forced to H and the logo (aspect kept, its largest
/// side about 22% of the code's width) is drawn centred on a plate of cleared, light-coloured modules.
pub fn render_rgba(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result<Rendered, QrError> {
if let Some(l) = logo {
check_logo_size(l.width(), l.height())?;
}
let (matrix, g, level_used) = prepare(text, level, style, logo.is_some())?;
let plate = logo.map(|l| Plate::new(&g, l.width(), l.height()));
let size = g.size_px();
let mut img = RgbaImage::from_pixel(size, size, Rgba(style.light));
let dark = Rgba(style.dark);
for my in 0..g.modules {
for mx in 0..g.modules {
if !matrix.is_dark(mx, my) || plate.as_ref().is_some_and(|p| p.contains(mx, my)) {
continue;
}
let (x0, y0) = ((g.quiet + mx) * g.scale, (g.quiet + my) * g.scale);
for y in y0..y0 + g.scale {
for x in x0..x0 + g.scale {
img.put_pixel(x, y, dark);
}
}
}
}
if let (Some(logo), Some(p)) = (logo, &plate) {
let scaled = imageops::resize(logo, p.logo_w, p.logo_h, imageops::FilterType::Lanczos3);
let (ox, oy) = (g.quiet * g.scale + p.logo_x, g.quiet * g.scale + p.logo_y);
for (x, y, src) in scaled.enumerate_pixels() {
let dst = img.get_pixel_mut(ox + x, oy + y);
*dst = over(*src, *dst);
}
}
Ok(Rendered { image: img, level_used, modules: g.modules, module_px: g.scale, size_px: size })
}
/// [`render_rgba`], encoded as PNG.
pub fn render_png(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result<Vec<u8>, QrError> {
encode_png(&render_rgba(text, level, style, logo)?.image)
}
/// Encodes an RGBA image (a [`Rendered::image`]) as PNG.
pub fn encode_png(image: &RgbaImage) -> Result<Vec<u8>, QrError> {
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(image.as_raw(), image.width(), image.height(), image::ExtendedColorType::Rgba8)
.map_err(|e| QrError::Encode(e.to_string()))?;
Ok(out)
}
pub(crate) fn check_logo_size(w: u32, h: u32) -> Result<(), QrError> {
if w == 0 || h == 0 {
return Err(QrError::Logo("the image is empty.".into()));
}
if w > MAX_LOGO_PX || h > MAX_LOGO_PX {
return Err(QrError::Logo(format!(
"it is {w} x {h} pixels; at most {MAX_LOGO_PX} pixels on each side is allowed. Use a smaller image."
)));
}
Ok(())
}
/// Straight-alpha "source over destination".
fn over(src: Rgba<u8>, dst: Rgba<u8>) -> Rgba<u8> {
let sa = f32::from(src[3]) / 255.0;
let da = f32::from(dst[3]) / 255.0;
let oa = sa + da * (1.0 - sa);
if oa <= 0.0 {
return Rgba([0, 0, 0, 0]);
}
let mix = |s: u8, d: u8| ((f32::from(s) * sa + f32::from(d) * da * (1.0 - sa)) / oa).round() as u8;
Rgba([mix(src[0], dst[0]), mix(src[1], dst[1]), mix(src[2], dst[2]), (oa * 255.0).round() as u8])
}