| 1 | use image::{GrayImage, Luma};
|
| 2 |
|
| 3 | use crate::dsl::{BarcodeSymbology, QrEcc};
|
| 4 |
|
| 5 | #[derive(Debug)]
|
| 6 | pub enum RasterError {
|
| 7 | Encode(String),
|
| 8 | Image(String),
|
| 9 | }
|
| 10 |
|
| 11 | impl std::fmt::Display for RasterError {
|
| 12 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
| 13 | match self {
|
| 14 | Self::Encode(msg) | Self::Image(msg) => write!(f, "{msg}"),
|
| 15 | }
|
| 16 | }
|
| 17 | }
|
| 18 |
|
| 19 | impl std::error::Error for RasterError {}
|
| 20 |
|
| 21 | pub fn render_barcode(
|
| 22 | symbology: BarcodeSymbology,
|
| 23 | data: &str,
|
| 24 | height: u32,
|
| 25 | ) -> Result<GrayImage, RasterError> {
|
| 26 | use barcoders::generators::image::Image as BarcodeImage;
|
| 27 | use barcoders::sym::codabar::Codabar;
|
| 28 | use barcoders::sym::code11::Code11;
|
| 29 | use barcoders::sym::code128::Code128;
|
| 30 | use barcoders::sym::code39::Code39;
|
| 31 | use barcoders::sym::code93::Code93;
|
| 32 | use barcoders::sym::ean13::UPCA;
|
| 33 | use barcoders::sym::ean13::EAN13;
|
| 34 | use barcoders::sym::ean8::EAN8;
|
| 35 | use barcoders::sym::tf::TF;
|
| 36 |
|
| 37 | let data = data.trim();
|
| 38 | if data.is_empty() {
|
| 39 | return Err(RasterError::Encode("Barcode data is empty".into()));
|
| 40 | }
|
| 41 |
|
| 42 | let encoded = match symbology {
|
| 43 | BarcodeSymbology::Code128 => {
|
| 44 | Code128::new(code128_barcoders_input(data))
|
| 45 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 46 | .encode()
|
| 47 | }
|
| 48 | BarcodeSymbology::Code39 => Code39::new(data)
|
| 49 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 50 | .encode(),
|
| 51 | BarcodeSymbology::Code93 => Code93::new(data)
|
| 52 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 53 | .encode(),
|
| 54 | BarcodeSymbology::Ean13 => EAN13::new(data)
|
| 55 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 56 | .encode(),
|
| 57 | BarcodeSymbology::Ean8 => EAN8::new(data)
|
| 58 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 59 | .encode(),
|
| 60 | BarcodeSymbology::UpcA => UPCA::new(data)
|
| 61 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 62 | .encode(),
|
| 63 | BarcodeSymbology::UpcE => {
|
| 64 | return Err(RasterError::Encode(
|
| 65 | "UPC-E raster is not supported; use native UPC-E".into(),
|
| 66 | ));
|
| 67 | }
|
| 68 | BarcodeSymbology::Itf => TF::interleaved(data)
|
| 69 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 70 | .encode(),
|
| 71 | BarcodeSymbology::Codabar => Codabar::new(data)
|
| 72 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 73 | .encode(),
|
| 74 | BarcodeSymbology::Code11 => Code11::new(data)
|
| 75 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 76 | .encode(),
|
| 77 | };
|
| 78 |
|
| 79 | let png = BarcodeImage::png(height);
|
| 80 | let bytes = png
|
| 81 | .generate(&encoded)
|
| 82 | .map_err(|e| RasterError::Image(e.to_string()))?;
|
| 83 | let img = image::load_from_memory(&bytes).map_err(|e| RasterError::Image(e.to_string()))?;
|
| 84 | Ok(img.to_luma8())
|
| 85 | }
|
| 86 |
|
| 87 | /// Stretch a barcode to exactly `target_width` dots, keeping the original height.
|
| 88 | ///
|
| 89 | /// Barcodes are widened to the full printable width so module bars stay
|
| 90 | /// wide enough to scan reliably.
|
| 91 | pub fn scale_gray_to_print_width(gray: GrayImage, target_width: u32) -> GrayImage {
|
| 92 | let (w, h) = gray.dimensions();
|
| 93 | if w == 0 || h == 0 || target_width == 0 {
|
| 94 | return gray;
|
| 95 | }
|
| 96 | if w == target_width {
|
| 97 | return gray;
|
| 98 | }
|
| 99 | image::imageops::resize(
|
| 100 | &gray,
|
| 101 | target_width,
|
| 102 | h,
|
| 103 | image::imageops::FilterType::Nearest,
|
| 104 | )
|
| 105 | }
|
| 106 |
|
| 107 | /// Prefix payload for `barcoders` Code128.
|
| 108 | ///
|
| 109 | /// The crate requires a leading charset marker. Set A (`\u{00C0}`) only supports
|
| 110 | /// uppercase letters; mixed-case and typical URLs need set B (`\u{0181}`).
|
| 111 | fn code128_barcoders_input(data: &str) -> String {
|
| 112 | let start = if data.chars().any(|c| c.is_ascii_lowercase()) {
|
| 113 | '\u{0181}' // Start B — upper + lower case
|
| 114 | } else {
|
| 115 | '\u{00C0}' // Start A — uppercase, digits, symbols
|
| 116 | };
|
| 117 | format!("{start}{data}")
|
| 118 | }
|
| 119 |
|
| 120 | pub fn render_qr(
|
| 121 | data: &str,
|
| 122 | version: Option<u8>,
|
| 123 | ecc: QrEcc,
|
| 124 | module_pixels: u32,
|
| 125 | ) -> Result<GrayImage, RasterError> {
|
| 126 | use qrcode::EcLevel;
|
| 127 | use qrcode::QrCode;
|
| 128 | use qrcode::Version;
|
| 129 |
|
| 130 | let ec = match ecc {
|
| 131 | QrEcc::L => EcLevel::L,
|
| 132 | QrEcc::M => EcLevel::M,
|
| 133 | QrEcc::Q => EcLevel::Q,
|
| 134 | QrEcc::H => EcLevel::H,
|
| 135 | };
|
| 136 |
|
| 137 | let code = if let Some(v) = version {
|
| 138 | let v = v.clamp(1, 40);
|
| 139 | QrCode::with_version(data.as_bytes(), Version::Normal(i16::from(v)), ec)
|
| 140 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 141 | } else {
|
| 142 | QrCode::with_error_correction_level(data.as_bytes(), ec)
|
| 143 | .map_err(|e| RasterError::Encode(e.to_string()))?
|
| 144 | };
|
| 145 |
|
| 146 | let width = code.width() as u32;
|
| 147 | let scale = module_pixels.max(1);
|
| 148 | let out_w = width * scale;
|
| 149 | let mut img = GrayImage::new(out_w, out_w);
|
| 150 | for y in 0..width {
|
| 151 | for x in 0..width {
|
| 152 | let dark = code[(x as usize, y as usize)] == qrcode::Color::Dark;
|
| 153 | let color = if dark { 0 } else { 255 };
|
| 154 | for dy in 0..scale {
|
| 155 | for dx in 0..scale {
|
| 156 | img.put_pixel(x * scale + dx, y * scale + dy, Luma([color]));
|
| 157 | }
|
| 158 | }
|
| 159 | }
|
| 160 | }
|
| 161 | Ok(img)
|
| 162 | }
|
| 163 |
|
| 164 | #[cfg(test)]
|
| 165 | mod tests {
|
| 166 | use super::*;
|
| 167 |
|
| 168 | #[test]
|
| 169 | fn barcode_stretches_to_print_width() {
|
| 170 | let narrow = render_barcode(BarcodeSymbology::Code128, "X", 60).unwrap();
|
| 171 | assert!(narrow.width() < 384);
|
| 172 | let original_h = narrow.height();
|
| 173 | let wide = scale_gray_to_print_width(narrow, 384);
|
| 174 | assert_eq!(wide.width(), 384);
|
| 175 | assert_eq!(wide.height(), original_h);
|
| 176 | }
|
| 177 |
|
| 178 | #[test]
|
| 179 | fn renders_code128_raster() {
|
| 180 | let img = render_barcode(BarcodeSymbology::Code128, "TEST123", 60).unwrap();
|
| 181 | assert!(img.width() > 10);
|
| 182 | assert_eq!(img.height(), 60);
|
| 183 | }
|
| 184 |
|
| 185 | #[test]
|
| 186 | fn renders_code128_mixed_case() {
|
| 187 | let img = render_barcode(BarcodeSymbology::Code128, "Testcode", 60).unwrap();
|
| 188 | assert!(img.width() > 10);
|
| 189 | assert_eq!(img.height(), 60);
|
| 190 | }
|
| 191 |
|
| 192 | #[test]
|
| 193 | fn code128_accepts_url_like_data() {
|
| 194 | let img = render_barcode(BarcodeSymbology::Code128, "https://example.com", 60).unwrap();
|
| 195 | assert!(img.width() > 10);
|
| 196 | }
|
| 197 |
|
| 198 | #[test]
|
| 199 | fn code128_rejects_empty_data() {
|
| 200 | let err = render_barcode(BarcodeSymbology::Code128, " ", 60).unwrap_err();
|
| 201 | assert!(err.to_string().contains("empty"));
|
| 202 | }
|
| 203 |
|
| 204 | #[test]
|
| 205 | fn renders_qr_raster_with_version() {
|
| 206 | let img = render_qr("https://example.com", Some(5), QrEcc::M, 4).unwrap();
|
| 207 | assert!(img.width() >= 20);
|
| 208 | }
|
| 209 | }
|