59 lines
2.0 KiB
Rust
59 lines
2.0 KiB
Rust
//! Helpers shared by the integration tests: decoding a rendered code back with rqrr.
|
|
|
|
#![allow(dead_code)]
|
|
|
|
use image::{DynamicImage, GrayImage, Rgba, RgbaImage};
|
|
|
|
/// Decodes the single QR code in `img` and returns its text and the ECC level rqrr read (0 = M, 1 = L, 2 = H, 3 = Q).
|
|
pub fn decode_gray(gray: GrayImage) -> (String, u16) {
|
|
let mut prepared = rqrr::PreparedImage::prepare(gray);
|
|
let grids = prepared.detect_grids();
|
|
assert_eq!(grids.len(), 1, "expected exactly one QR code in the image, found {}", grids.len());
|
|
let (meta, content) = grids[0].decode().expect("the QR code should decode");
|
|
(content, meta.ecc_level)
|
|
}
|
|
|
|
pub fn decode(img: &RgbaImage) -> String {
|
|
decode_with_level(img).0
|
|
}
|
|
|
|
pub fn decode_with_level(img: &RgbaImage) -> (String, u16) {
|
|
decode_gray(DynamicImage::ImageRgba8(img.clone()).to_luma8())
|
|
}
|
|
|
|
/// rqrr's `ecc_level` numbering is the format-information encoding: M = 0, L = 1, H = 2, Q = 3.
|
|
pub fn rqrr_level(level: pictor_qr::Level) -> u16 {
|
|
match level {
|
|
pictor_qr::Level::M => 0,
|
|
pictor_qr::Level::L => 1,
|
|
pictor_qr::Level::H => 2,
|
|
pictor_qr::Level::Q => 3,
|
|
}
|
|
}
|
|
|
|
/// A logo: a filled red circle on a yellow square, with a transparent border.
|
|
pub fn logo(w: u32, h: u32) -> RgbaImage {
|
|
let mut img = RgbaImage::from_pixel(w, h, Rgba([0, 0, 0, 0]));
|
|
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
|
|
let r = (w.min(h) as f64) * 0.35;
|
|
for y in 0..h {
|
|
for x in 0..w {
|
|
let border = x < w / 10 || y < h / 10 || x >= w - w / 10 || y >= h - h / 10;
|
|
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
|
|
let px = if dx * dx + dy * dy <= r * r {
|
|
Rgba([200, 20, 40, 255])
|
|
} else if border {
|
|
Rgba([0, 0, 0, 0])
|
|
} else {
|
|
Rgba([240, 200, 30, 255])
|
|
};
|
|
img.put_pixel(x, y, px);
|
|
}
|
|
}
|
|
img
|
|
}
|
|
|
|
pub fn logo_png(w: u32, h: u32) -> Vec<u8> {
|
|
pictor_qr::encode_png(&logo(w, h)).expect("logo PNG")
|
|
}
|