40 lines
1.3 KiB
Rust
40 lines
1.3 KiB
Rust
use crate::qr::QrCode;
|
|
use image::{ImageBuffer, Luma};
|
|
|
|
pub fn render_png(qr: &QrCode, module_size: u8) -> Result<Vec<u8>, image::ImageError> {
|
|
let matrix_size = qr.size() as u32;
|
|
let margin = qr.margin as u32;
|
|
let total_size = matrix_size + 2 * margin;
|
|
let img_size = total_size * module_size as u32;
|
|
|
|
let mut img = ImageBuffer::new(img_size, img_size);
|
|
|
|
for y in 0..total_size {
|
|
for x in 0..total_size {
|
|
let module_x = x.saturating_sub(margin);
|
|
let module_y = y.saturating_sub(margin);
|
|
|
|
let is_dark = if module_x < matrix_size && module_y < matrix_size {
|
|
qr.modules()[module_y as usize][module_x as usize]
|
|
} else {
|
|
false // 白边
|
|
};
|
|
|
|
let px_val = if is_dark { 0u8 } else { 255u8 };
|
|
for dy in 0..module_size as u32 {
|
|
for dx in 0..module_size as u32 {
|
|
img.put_pixel(
|
|
x * module_size as u32 + dx,
|
|
y * module_size as u32 + dy,
|
|
Luma([px_val]),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut buf = Vec::new();
|
|
img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)?;
|
|
Ok(buf)
|
|
}
|