diff --git a/src/helpers.rs b/src/helpers.rs new file mode 100644 index 0000000..f03517a --- /dev/null +++ b/src/helpers.rs @@ -0,0 +1,70 @@ +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + rc::Rc, +}; + +use crate::{ + common::HybridBinarizer, + multi::{GenericMultipleBarcodeReader, MultipleBarcodeReader}, + BarcodeFormat, BinaryBitmap, BufferedImageLuminanceSource, DecodeHintType, DecodeHintValue, + DecodingHintDictionary, Exceptions, MultiFormatReader, RXingResult, Reader, +}; + +pub fn detect_in_file( + file_name: &str, + barcode_type: Option, +) -> Result { + detect_in_file_with_hints(file_name, barcode_type, &mut HashMap::new()) +} + +pub fn detect_in_file_with_hints( + file_name: &str, + barcode_type: Option, + hints: &mut DecodingHintDictionary, +) -> Result { + let img = image::open(file_name).unwrap(); + let mut multi_format_reader = MultiFormatReader::default(); + + if let Some(bc_type) = barcode_type { + hints.insert( + DecodeHintType::POSSIBLE_FORMATS, + DecodeHintValue::PossibleFormats(HashSet::from([bc_type])), + ); + } + + if !hints.contains_key(&DecodeHintType::TRY_HARDER) { + hints.insert(DecodeHintType::TRY_HARDER, DecodeHintValue::TryHarder(true)); + } + + multi_format_reader.decode_with_hints( + &mut BinaryBitmap::new(Rc::new(RefCell::new(HybridBinarizer::new(Box::new( + BufferedImageLuminanceSource::new(img), + ))))), + &hints, + ) +} + +pub fn detect_multiple_in_file(file_name: &str) -> Result, Exceptions> { + detect_multiple_in_file_with_hints(file_name, &mut HashMap::new()) +} + +pub fn detect_multiple_in_file_with_hints( + file_name: &str, + hints: &mut DecodingHintDictionary, +) -> Result, Exceptions> { + let img = image::open(file_name).unwrap(); + let multi_format_reader = MultiFormatReader::default(); + let mut scanner = GenericMultipleBarcodeReader::new(multi_format_reader); + + if !hints.contains_key(&DecodeHintType::TRY_HARDER) { + hints.insert(DecodeHintType::TRY_HARDER, DecodeHintValue::TryHarder(true)); + } + + scanner.decode_multiple_with_hints( + &mut BinaryBitmap::new(Rc::new(RefCell::new(HybridBinarizer::new(Box::new( + BufferedImageLuminanceSource::new(img), + ))))), + &hints, + ) +} diff --git a/src/lib.rs b/src/lib.rs index c80d6cc..6e63618 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -93,3 +93,6 @@ pub use multi_format_writer::*; mod multi_format_reader; pub use multi_format_reader::*; + +// Simple methods to help detect barcodes in common situations +pub mod helpers; \ No newline at end of file