rxing

repository·main·Indexed 43 days ago

https://github.com/rxing-core/rxing

A pure Rust port of the ZXing Java barcode library, including enhancements from zxing-cpp. It provides comprehensive support for encoding and decoding a wide variety of 1D and 2D barcode symbologies, including QR Codes, Aztec, Data Matrix, and PDF417. Version 0.9.3 supports granular feature flags to optimize build size and includes a command-line interface via rxing-cli.

Tokens
15.6K
Snippets
53
Records
64
Agent score
54%

What's inside rxing

  1. Configure Encode/Decode hints using configuration structs

    main

    As of v0.7.0, rxing has migrated away from using HashMap-based Encode/Decode hints. Instead, the library uses dedicated configuration structs.

    If you are migrating from an older version, you can construct these new configuration structs using From and Into implementations that support the legacy HashMap format.

  2. Use ImmutableReader for thread-safe or static decoding

    main

    Many 2D readers in rxing implement the ImmutableReader trait. This allows you to call immutable_decode or immutable_decode_with_hints without requiring the reader instance to be declared as mutable (mut).

    This is particularly useful for using individual symbol readers in a Lazy static context without requiring unsafe code.

    Note: Not all readers support this. The following readers do not implement ImmutableReader because they require internal state:

    • MultiFormatReader
    • MultiUseMultiFormatReader
    • FilteredImageReader
    • MultiFormatOneDReader
    static LAZY_STATIC_QR_READER: Lazy<QRCodeReader> = Lazy::new(QRCodeReader::default);
    
    fn main() {
        let result = LAZY_STATIC_QR_READER.immutable_decode(
            &mut BinaryBitmap::new(
                HybridBinarizer::new(
                    Luma8LuminanceSource::new(luma_data, width, height),
                )
            )
        );
    }
  3. Optimize build size using granular feature flags

    main

    Starting from v0.9.0, rxing allows for highly granular builds. By setting default-features = false in your Cargo.toml, you can include only the specific symbologies and capabilities required for your application, significantly reducing binary size and dependencies.

    Example: Decoding only QR Codes

    To build a minimal program that only decodes QR codes, use these features: image, image_formats, encoding_rs, decoders, qrcode

    Example: Encoding only Aztec codes

    To build a minimal program that only encodes Aztec codes, use these features: image, image_formats, encoding_rs, encoders, aztec

    # Example Cargo.toml configuration for minimal QR decoding
    [dependencies]
    rxing = {
        version = "0.9.3",
        default-features = false,
        features = ["image", "image_formats", "encoding_rs", "decoders", "qrcode"]
    }
  4. Install rxing via Cargo

    main

    To use rxing in your Rust project, add it to your Cargo.toml dependencies or use the cargo add command.

    Note: The library requires a minimum Rust version of 1.85. Versions below this are untested and may not compile.

    cargo add rxing
  5. Configure rxing feature flags

    main

    You can customize the library's capabilities using Cargo feature flags. The default feature set includes image, client_support, image_formats, serde, encoding_rs, encoders, decoders, full_barcode_format_support, and multi_barcode_readers.

    Core & Engine

    • image (default): Required for image manipulation and reading.
    • image_formats (default): Enables support for all image crate formats.
    • encoders (default): Enables barcode encoding.
    • decoders (default): Enables barcode decoding.
    • multi_barcode_readers (default): Enables reading multiple barcodes in one image.
    • client_support (default): Enables parsing barcode result types (e.g., URLs, contacts, WiFi).
    • serde (default): Adds serde::Serialize and serde::Deserialize support to public structs.
    • encoding_rs (default): Uses encoding_rs for high-performance character encoding.

    Symbology Granular Support

    • full_barcode_format_support (default): Enables all modules listed below.
    • aztec: Aztec barcodes.
    • datamatrix: Data Matrix barcodes.
    • maxicode: MaxiCode barcodes.
    • oned: 1D barcodes.
    • pdf417: PDF417 barcodes.
    • qrcode: QR Code barcodes.

    Advanced & Optional

    • allow_forced_iso_ied_18004_compliance: Force ISO/IED 18004 compliance (use with caution).
    • legacy_encoding: Uses the legacy encoding crate for exact compatibility with older versions.
    • no_character_set_support: Disables all CharacterSet support.
    • otsu_level: Adds OtsuLevelBinarizer (untested).
    • reverse_pyramid_layers: Reverses pyramid scan order for FilteredImageReader.
    • svg_read: Enable SVG file reading.
    • svg_write: Enable SVG file writing.
    • wasm_support: Enables WASM compatibility.
    • experimental_features: Enables risky experimental features.
  6. Configure decoding and encoding with Hint Dictionaries

    main

    rxing uses specialized HashMap types to pass configuration parameters to the decoding and encoding engines. These dictionaries allow you to fine-tune the behavior of readers and writers.

    • Decoding: Use DecodingHintDictionary (a HashMap<DecodeHintType, DecodeHintValue>) to provide hints to the Reader.
    • Encoding: Use EncodingHintDictionary (a HashMap<EncodeHintType, EncodeHintValue>) to provide hints to the Writer.
    • Result Metadata: Use MetadataDictionary (a HashMap<RXingResultMetadataType, RXingResultMetadataValue>) to access metadata returned within an RXingResult.
  7. Use BinaryBitmap for 1-bit image representation

    main

    The BinaryBitmap<B> struct is the core representation of 1-bit data used by ZXing readers to decode barcodes. It wraps a Binarizer and provides access to the binarized image data as either rows, lines, or a full 2D matrix.

    Key characteristics:

    • Lazy Evaluation: The 2D matrix is computed lazily and cached to avoid expensive re-computation.
    • Copy-on-Write: Using get_black_matrix_mut() creates a local copy of the binarizer's cache if you need to perform mutations (like inversion), ensuring the original binarizer's cache remains uncorrupted.
    • Inversion Support: You can toggle between normal and inverted views using invert(), which is useful for decoders that need to attempt reading both black-on-white and white-on-black images.
    // Example initialization (requires a Binarizer implementation)
    let binarizer = MyBinarizer::new(my_luminance_source);
    let bitmap = BinaryBitmap::new(binarizer);
    
    // Accessing the 2D matrix
    let matrix = bitmap.get_black_matrix();
    
    // Inverting the view
    let mut mutable_bitmap = bitmap;
    mutable_bitmap.invert();
  8. Use GenericGFPoly for Reed-Solomon polynomial arithmetic

    main

    GenericGFPoly represents an immutable polynomial whose coefficients are elements of a Galois Field (GenericGF). It is used for performing polynomial arithmetic required by Reed-Solomon error correction.

    Key behaviors:

    • Coefficient Order: Coefficients are provided from most significant (highest-power term) to least significant.
    • Immutability: Instances are immutable; arithmetic operations return new GenericGFPoly instances.
    • Field Consistency: Arithmetic operations like addOrSubtract, multiply, and divide require that both polynomials belong to the same GenericGF field. Attempting to operate on polynomials from different fields will return an error.
    • Zero Polynomial: A polynomial where all coefficients are zero is treated as the monomial "0".
    // Example of creating a polynomial from coefficients
    // Note: coefficients are most-significant first
    let poly = GenericGFPoly::new(field_ref, &[1, 0, 3])?; // Represents 1x^2 + 0x + 3
  9. Use rxing helpers to detect multiple barcodes in a file

    main

    The rxing::helpers module provides high-level functions for common tasks. detect_multiple_in_file can be used to scan an image file for all present barcodes and return their formats and text content.

    fn main() {
        let file_name = "test_image.jpg";
    
        let results = rxing::helpers::detect_multiple_in_file(file_name).expect("decodes");
    
        for result in results {
            println!("{} -> {}", result.getBarcodeFormat(), result.getText())
        }
    }