use image::{Rgba, RgbaImage};
use rxing::aztec::AztecWriter;
use rxing::{BarcodeFormat, EncodeHintValue, EncodeHints, Writer};
pub fn encode(content: &str, magnification: i32, ec_symbol_size: i32) -> Result<RgbaImage, String> {
if content.is_empty() {
return Err("Aztec: empty content".to_string());
}
let mag = magnification.max(1) as u32;
let writer = AztecWriter;
let mut hints = EncodeHints::default();
hints = hints.with(EncodeHintValue::Margin("0".to_string()));
match ec_symbol_size {
101..=104 => {
let layers = -(ec_symbol_size - 100);
hints = hints.with(EncodeHintValue::AztecLayers(layers));
}
201..=232 => {
let layers = ec_symbol_size - 200;
hints = hints.with(EncodeHintValue::AztecLayers(layers));
}
1..=99 => {
let adjusted_ec =
(ec_symbol_size * 100 + (100 - ec_symbol_size) - 1) / (100 - ec_symbol_size);
hints = hints.with(EncodeHintValue::ErrorCorrection(adjusted_ec.to_string()));
}
_ => {}
}
let bit_matrix = writer
.encode_with_hints(content, &BarcodeFormat::AZTEC, 0, 0, &hints)
.map_err(|e| format!("Aztec encoding failed: {}", e))?;
let bm_width = bit_matrix.getWidth();
let bm_height = bit_matrix.getHeight();
let img_width = bm_width * mag;
let img_height = bm_height * mag;
let mut img = RgbaImage::from_pixel(img_width, img_height, Rgba([0, 0, 0, 0]));
let black = Rgba([0, 0, 0, 255]);
for y in 0..bm_height {
for x in 0..bm_width {
if bit_matrix.get(x, y) {
let px = x * mag;
let py = y * mag;
for dy in 0..mag {
for dx in 0..mag {
img.put_pixel(px + dx, py + dy, black);
}
}
}
}
}
Ok(img)
}