qrcode-rust

repository·master·Indexed 19 days ago

https://github.com/kennytm/qrcode-rust

A Rust library for encoding data into standard QR codes and Micro QR codes (version 0.14.1). It supports multiple rendering formats including images (via the image crate), SVG, Unicode strings, PIC, and EPS. The library provides a Canvas API for manual QR code construction, including support for various MaskPatterns and error correction levels (L, M, Q, H).

Tokens
7.9K
Snippets
39
Records
44
Agent score
68%

What's inside qrcode

  1. Install the qrcode crate

    master

    Add qrcode to your Cargo.toml dependencies. By default, it includes features for image generation via the image crate. If you only need to encode data and do not require image generation capabilities, you can disable default features to reduce dependencies.

    # Standard installation with image generation support
    [dependencies]
    qrcode = "0.14.1"
    
    # Minimal installation without image generation
    [dependencies]
    qrcode = { version = "0.14.1", default-features = false, features = ["std"] }
  2. Configure Error Correction Levels with EcLevel

    master

    The EcLevel enum defines the error correction capability of the QR code, allowing data recovery even if parts of the code are damaged. Higher levels provide more protection but reduce the amount of data that can be stored.

    • L: Low error correction (up to 7% recovery).
    • M: Medium error correction (up to 15% recovery) - Default.
    • Q: Quartile error correction (up to 25% recovery).
    • H: High error correction (up to 30% recovery).
    #[derive(Debug, PartialEq, Eq, Copy, Clone, PartialOrd, Ord)]
    pub enum EcLevel {
        L = 0,
        M = 1,
        Q = 2,
        H = 3,
    }
  3. Choose the correct Data Mode

    master

    The Mode enum specifies the character set used for encoding. Choosing the most restrictive mode that fits your data optimizes space.

    • Numeric: Only digits 0-9.
    • Alphanumeric: Uppercase letters (A-Z), numbers (0-9), and specific punctuation ( , $, %, *, +, -, ., /, :).
    • Byte: Arbitrary binary data.
    • Kanji: Shift-JIS-encoded double-byte text.

    Use Mode::max(other) to find the lowest common mode that can accommodate both sets of characters (e.g., Numeric.max(Kanji) returns Byte).

    # use qrcode::types::Mode;
    let a = Mode::Numeric;
    let b = Mode::Kanji;
    let c = a.max(b);
    assert!(a <= c);
    assert!(b <= c);
  4. How the Renderer calculates image dimensions

    master

    The Renderer ensures that modules maintain a uniform size (no distortion) by calculating a single module_size based on your constraints.

    • min_dimensions(width, height): If you request a minimum size of 200x200 for a QR code with 19 modules (including quiet zone), the renderer calculates that each module must be at least 11x11 pixels, resulting in a final image of 209x209 pixels.
    • max_dimensions(width, height): If you request a maximum size of 200x200, the renderer calculates that each module should be 10x10 pixels, resulting in a final image of 190x190 pixels.
    • module_dimensions(width, height): Directly sets the pixel width and height for every module.
  5. Use the Canvas API to render a QR code

    master

    The Canvas struct is an intermediate helper used to render error-corrected data into a QR code. You can construct a new canvas by specifying a Version and an EcLevel, then populate it by drawing functional patterns (like finder patterns) and data bits.

    To prepare a canvas for data placement, use draw_all_functional_patterns(). This fills in finder patterns, alignment patterns, timing patterns, and version info, while reserving space for format info. You can then use draw_data() to place the actual QR content.

    Note: draw_all_functional_patterns() fills the format info area with light modules to ensure data bits can be placed in the remaining empty modules.

    use qrcode::canvas::{Canvas, MaskPattern};
    use qrcode::types::{EcLevel, Version};
    
    let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
    c.draw_all_functional_patterns();
    c.draw_data(b"data_here", b"ec_code_here");
    c.apply_mask(MaskPattern::Checkerboard);
    let bools = c.to_bools();
  6. Generate a QR code using Unicode characters

    master

    For high-density terminal output, use qrcode::render::unicode. You can specify render patterns like unicode::Dense1x2 and set colors using unicode::Dense1x2::Light or unicode::Dense1x2::Dark.

    use qrcode::QrCode;
    use qrcode::render::unicode;
    
    fn main() {
        let code = QrCode::new("mow mow").unwrap();
        let image = code.render::<unicode::Dense1x2>()
            .dark_color(unicode::Dense1x2::Light)
            .light_color(unicode::Dense1x2::Dark)
            .build();
        println!("{image}");
    }
  7. Generate a QR code as an image

    master

    To generate a QR code as an image file, use QrCode::new() to encode your data and then call .render::<T>() where T is a type from the image crate (e.g., Luma<u8>).

    use qrcode::QrCode;
    use image::Luma;
    
    fn main() {
        // Encode some data into bits.
        let code = QrCode::new(b"01234567").unwrap();
    
        // Render the bits into an image.
        let image = code.render::<Luma<u8>>().build();
    
        // Save the image.
        image.save("/tmp/qrcode.png").unwrap();
    }
  8. Generate a QR code as a string of characters

    master

    You can render a QR code into a string using characters (like #) by specifying char as the render type. You can customize the appearance using methods like .dark_color(), .quiet_zone(), and .module_dimensions().

    use qrcode::QrCode;
    
    fn main() {
        let code = QrCode::new(b"Hello").unwrap();
        let string = code.render::<char>()
            .dark_color('#')
            .quiet_zone(false)
            .module_dimensions(2, 1)
            .build();
        println!("{string}");
    }
  9. Generate a QR code as EPS (Encapsulated PostScript)

    master

    To generate EPS output, use qrcode::render::eps. You can define colors using eps::Color which accepts an array of RGB values (e.g., [0.5, 0.0, 0.0]).

    use qrcode::render::eps;
    use qrcode::{EcLevel, QrCode, Version};
    
    fn main() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code.render()
            .min_dimensions(200, 200)
            .dark_color(eps::Color([0.5, 0.0, 0.0]))
            .light_color(eps::Color([1.0, 1.0, 0.5]))
            .build();
        println!("{image}");
    }
  10. Generate a QR code as an SVG

    master

    To generate an SVG, use QrCode::with_version() to specify version and error correction level (e.g., Version::Micro(2) and EcLevel::L). Use .render() with SVG-specific color types from qrcode::render::svg.

    use qrcode::{QrCode, Version, EcLevel};
    use qrcode::render::svg;
    
    fn main() {
        let code = QrCode::with_version(b"01234567", Version::Micro(2), EcLevel::L).unwrap();
        let image = code.render()
            .min_dimensions(200, 200)
            .dark_color(svg::Color("#800000"))
            .light_color(svg::Color("#ffff80"))
            .build();
        println!("{image}");
    }
  11. Generate a QR code as PIC markup

    master

    Use qrcode::render::pic to generate PIC (Pixar Image Computer) markup. This is useful for vector-based graphics in specific environments.

    use qrcode::render::pic;
    use qrcode::QrCode;
    
    fn main() {
        let code = QrCode::new(b"01234567").unwrap();
        let image = code
            .render::<pic::Color>()
            .min_dimensions(1, 1)
            .build();
        println!("{image}");
    }
  12. Render QR codes as UTF-8 strings using Dense1x2

    master

    You can render a QR code as a high-density UTF-8 string where each character represents a 1x2 block of pixels. This is achieved using the Dense1x2 pixel type. This method is useful for displaying QR codes in terminal environments or text-based interfaces.

    To use this, call .render::<Dense1x2>() on a QrCode instance. You can customize the appearance using .dark_color() and .light_color() to invert the colors, and specify the module dimensions with .module_dimensions(width, height).

    use qrcode::{QrCode, Version, EcLevel};
    use qrcode::render::unicode::Dense1x2;
    
    let code = QrCode::with_version(b"09876542", Version::Micro(2), EcLevel::L).unwrap();
    let image = code
        .render::<Dense1x2>()
        .module_dimensions(1, 1)
        .build();
    
    println!("{}", image);