libhardcopy 1.0.1

Generalized library for hardcopy/softcopy command line utilities.
Documentation
// QR code version 15 at Low error correction holds up to 555 binary bytes.
// Staying well under that keeps the code at ~77x77 modules — dense enough
// to hold meaningful data but small enough for a phone to reliably scan.
const QR_MAX_BYTES: usize = 500;

use crate::{HardCopySection, HardCopySectionContent};
use ::image::{DynamicImage, ImageOutputFormat, Luma};
use ::qrcode::{EcLevel, QrCode};
use std::io::Cursor;

/// Encode `bytes` into one or more QR code PNG sections.
///
/// Large inputs are chunked so each QR code stays within the version-40
/// binary capacity at Low error correction (2953 bytes).
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");
    // Render at 1200x1200 minimum so each module is ~15px at version 15,
    // making the code easy for a phone camera to resolve.
    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
}