const QR_MAX_BYTES: usize = 500;
use crate::{HardCopySection, HardCopySectionContent};
use ::image::{DynamicImage, ImageOutputFormat, Luma};
use ::qrcode::{EcLevel, QrCode};
use std::io::Cursor;
pub fn bytes_to_qr_sections(bytes: &[u8]) -> Vec<HardCopySection> {
let chunks: Vec<&[u8]> = bytes.chunks(QR_MAX_BYTES).collect();
let total = chunks.len();
chunks
.into_iter()
.enumerate()
.map(|(i, chunk)| {
let name = if total == 1 {
"QR Code".to_string()
} else {
format!("QR Code {}/{}", i + 1, total)
};
HardCopySection {
name,
content: HardCopySectionContent::Bytes(encode_chunk(chunk)),
}
})
.collect()
}
fn encode_chunk(data: &[u8]) -> Vec<u8> {
let code =
QrCode::with_error_correction_level(data, EcLevel::L).expect("Failed to generate QR code");
let gray = code.render::<Luma<u8>>().min_dimensions(1200, 1200).build();
let mut png_bytes = Vec::new();
DynamicImage::ImageLuma8(gray)
.write_to(&mut Cursor::new(&mut png_bytes), ImageOutputFormat::Png)
.expect("Failed to encode QR code as PNG");
png_bytes
}