48 lines
1.9 KiB
Rust
48 lines
1.9 KiB
Rust
use anyhow::{Context, Result};
|
|
use eframe::egui::ColorImage;
|
|
use qrcode::{types::Color, EcLevel, QrCode};
|
|
|
|
const QUIET_MODULES: usize = 4;
|
|
|
|
/// Active optical renderer. QFT2/Base45 text uses only QR alphanumeric
|
|
/// characters, allowing the QR encoder to choose a compact alphanumeric data
|
|
/// mode. Exact integer module pixels + full quiet zone maximize camera clarity.
|
|
pub fn render_qr_fitted(text: &str, target_side: usize) -> Result<ColorImage> {
|
|
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::L)
|
|
.context("QR payload too large")?;
|
|
let modules = code.width() + QUIET_MODULES * 2;
|
|
let scale = (target_side / modules).max(1);
|
|
let side = modules * scale;
|
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
|
}
|
|
|
|
/// Pairing QR stays static and uses M error correction for first-scan reliability.
|
|
pub fn render_pair_qr(text: &str, target_side: usize) -> Result<ColorImage> {
|
|
let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)
|
|
.context("pair QR payload too large")?;
|
|
let modules = code.width() + QUIET_MODULES * 2;
|
|
let scale = (target_side / modules).max(1);
|
|
let side = modules * scale;
|
|
Ok(ColorImage::from_gray([side, side], &render_code_gray(&code, side)))
|
|
}
|
|
|
|
fn render_code_gray(code: &QrCode, side: usize) -> Vec<u8> {
|
|
let qr_width = code.width();
|
|
let modules = qr_width + QUIET_MODULES * 2;
|
|
let scale = (side / modules).max(1);
|
|
let actual_side = modules * scale;
|
|
let mut gray = vec![255u8; actual_side * actual_side];
|
|
for y in 0..qr_width {
|
|
for x in 0..qr_width {
|
|
if code[(x, y)] != Color::Dark { continue; }
|
|
let px0 = (x + QUIET_MODULES) * scale;
|
|
let py0 = (y + QUIET_MODULES) * scale;
|
|
for py in py0..py0 + scale {
|
|
let row = py * actual_side;
|
|
gray[row + px0..row + px0 + scale].fill(0);
|
|
}
|
|
}
|
|
}
|
|
gray
|
|
}
|