Skip to main content

QrCode

Struct QrCode 

Source
pub struct QrCode { /* private fields */ }
Expand description

The encoded QR code symbol.

QrCode is Send + Sync, so it can be shared or moved across threads (e.g. for parallel rendering of many codes). This is verified at compile time below.

Implementations§

Source§

impl QrCode

Source

pub fn new<D: AsRef<[u8]>>(data: D) -> QrResult<Self>

Constructs a new QR code which automatically encodes the given data.

This method uses the “medium” error correction level and automatically chooses the smallest QR code.

use qrcode_rs::QrCode;

let code = QrCode::new(b"Some data").unwrap();
§Errors

Returns error if the QR code cannot be constructed, e.g. when the data is too long.

Source

pub fn with_error_correction_level<D: AsRef<[u8]>>( data: D, ec_level: EcLevel, ) -> QrResult<Self>

Constructs a new QR code which automatically encodes the given data at a specific error correction level.

This method automatically chooses the smallest QR code.

use qrcode_rs::{QrCode, EcLevel};

let code = QrCode::with_error_correction_level(b"Some data", EcLevel::H).unwrap();
§Errors

Returns error if the QR code cannot be constructed, e.g. when the data is too long.

Source

pub fn new_micro<D: AsRef<[u8]>>(data: D) -> QrResult<Self>

Constructs a new Micro QR code which automatically encodes the given data.

This method uses the “medium” error correction level and automatically chooses the smallest Micro QR code.

use qrcode_rs::QrCode;

let code = QrCode::new_micro(b"123").unwrap();
§Errors

Returns error if the data cannot be encoded as a Micro QR code, e.g. when the data is too long.

Source

pub fn micro_with_error_correction_level<D: AsRef<[u8]>>( data: D, ec_level: EcLevel, ) -> QrResult<Self>

Constructs a new Micro QR code which automatically encodes the given data at a specific error correction level.

This method automatically chooses the smallest Micro QR code.

use qrcode_rs::{QrCode, EcLevel};

let code = QrCode::micro_with_error_correction_level(b"123", EcLevel::L).unwrap();
§Errors

Returns error if the data cannot be encoded as a Micro QR code, e.g. when the data is too long, or when the error correction level is not supported by any Micro QR version.

Source

pub fn with_version<D: AsRef<[u8]>>( data: D, version: Version, ec_level: EcLevel, ) -> QrResult<Self>

Constructs a new QR code for the given version and error correction level.

use qrcode_rs::{QrCode, Version, EcLevel};

let code = QrCode::with_version(b"Some data", Version::Normal(5), EcLevel::M).unwrap();

This method can also be used to generate Micro QR code.

use qrcode_rs::{QrCode, Version, EcLevel};

let micro_code = QrCode::with_version(b"123", Version::Micro(1), EcLevel::L).unwrap();
§Errors

Returns error if the QR code cannot be constructed, e.g. when the data is too long, or when the version and error correction level are incompatible.

Source

pub fn with_const_version<const N: i16, D: AsRef<[u8]>>( data: D, ec_level: EcLevel, ) -> QrResult<Self>

Constructs a new QR code with a compile-time checked normal QR version.

N must be in 1..=40. Invalid values fail during const evaluation when this fixed-version path is monomorphized.

use qrcode_rs::{EcLevel, QrCode, Version};

let code = QrCode::with_const_version::<5, _>(b"Some data", EcLevel::M).unwrap();
assert_eq!(code.version(), Version::Normal(5));
use qrcode_rs::{EcLevel, QrCode};

let _ = QrCode::with_const_version::<41, _>(b"Some data", EcLevel::M);
§Errors

Returns error if the QR code cannot be constructed for version N, e.g. when the data is too long for that version and error correction level.

Source

pub fn with_bits(bits: Bits, ec_level: EcLevel) -> QrResult<Self>

Constructs a new QR code with encoded bits.

Use this method only if there are very special need to manipulate the raw bits before encoding. Some examples are:

  • Encode data using specific character set with ECI
  • Use the FNC1 modes
  • Avoid the optimal segmentation algorithm

See the Bits structure for detail.

#![allow(unused_must_use)]

use qrcode_rs::{QrCode, Version, EcLevel};
use qrcode_rs::bits::Bits;

let mut bits = Bits::new(Version::Normal(1));
bits.push_eci_designator(9);
bits.push_byte_data(b"\xca\xfe\xe4\xe9\xea\xe1\xf2 QR");
bits.push_terminator(EcLevel::L);
let qrcode = QrCode::with_bits(bits, EcLevel::L);
§Errors

Returns error if the QR code cannot be constructed, e.g. when the bits are too long, or when the version and error correction level are incompatible.

Source

pub fn batch<I, D>(inputs: I, ec_level: EcLevel) -> QrResult<Vec<Self>>
where I: IntoIterator<Item = D>, D: AsRef<[u8]>,

Encodes many inputs at once at the given error-correction level, stopping at the first input that fails to encode.

§Examples
use qrcode_rs::{QrCode, EcLevel};

let codes = QrCode::batch(&["alpha", "beta", "gamma"], EcLevel::M).unwrap();
assert_eq!(codes.len(), 3);
Source

pub fn stream<I, D>(inputs: I) -> QrCodeStream<I::IntoIter>
where I: IntoIterator<Item = D>, D: AsRef<[u8]>,

Lazily encodes inputs into QR codes with the default error-correction level.

Unlike batch, this returns an iterator and does not collect every generated code into memory.

§Examples
use qrcode_rs::{EcLevel, QrCode};

let widths = QrCode::stream(["alpha", "beta"])
    .map(|code| code.map(|code| (code.error_correction_level(), code.width())))
    .collect::<Result<Vec<_>, _>>()
    .unwrap();

assert_eq!(widths, vec![(EcLevel::M, 21), (EcLevel::M, 21)]);
Source

pub fn stream_with_error_correction_level<I, D>( inputs: I, ec_level: EcLevel, ) -> QrCodeStream<I::IntoIter>
where I: IntoIterator<Item = D>, D: AsRef<[u8]>,

Lazily encodes inputs into QR codes at ec_level.

The iterator yields one QrResult<QrCode> per input, so callers can stop at the first error with collect::<Result<Vec<_>, _>>() or handle errors per item while keeping memory usage bounded by the active item.

Source

pub const fn version(&self) -> Version

Gets the version of this QR code.

Source

pub const fn error_correction_level(&self) -> EcLevel

Gets the error correction level of this QR code.

Source

pub const fn width(&self) -> usize

Gets the number of modules per side, i.e. the width of this QR code.

The width here does not contain the quiet zone paddings.

Source

pub fn max_allowed_errors(&self) -> usize

Gets the maximum number of allowed erratic modules can be introduced before the data becomes corrupted. Note that errors should not be introduced to functional modules.

Source

pub fn info(&self) -> Info

Returns metadata about this QR code (version, error-correction level, dimensions, module count, error tolerance, and data capacity).

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hello").unwrap();
let info = code.info();
assert_eq!(info.width(), code.width());
assert_eq!(info.module_count(), code.width() * code.width());
assert!(info.data_capacity_bytes() > 0);
Source

pub fn analyze(&self) -> Analysis

Returns diagnostic stats for this code: dark-module ratio and the split between functional and data modules. Combine with QrCode::info for version / capacity. Computed on demand (scans the grid).

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hello").unwrap();
let a = code.analyze();
assert!(a.dark_ratio() > 0.0 && a.dark_ratio() < 1.0);
assert_eq!(a.functional_modules() + a.data_modules(), code.width() * code.width());
Source

pub fn is_functional(&self, x: usize, y: usize) -> bool

Checks whether a module at coordinate (x, y) is a functional module or not.

Source

pub fn to_debug_str(&self, on_char: char, off_char: char) -> String

Converts the QR code into a human-readable string. This is mainly for debugging only.

Source

pub fn colors(&self) -> &[Color]

Returns the module colors as a borrowed slice — no allocation. Use this in preference to to_colors when you only need to read the modules.

The slice is row-major, with width() * width() entries and no quiet zone.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hi").unwrap();
let colors = code.colors();
assert_eq!(colors.len(), code.width() * code.width());
Source

pub fn module_view(&self) -> ModuleView<'_>

Returns a borrowed, read-only module-grid view.

This is the facade-friendly ModuleSource adapter for APIs that accept a borrowed QR module source without needing ownership of the full QrCode.

§Examples
use qrcode_rs::{ModuleSource, QrCode};

let code = QrCode::new(b"hi").unwrap();
let view = code.module_view();
assert_eq!(view.width(), code.width());
assert_eq!(view.modules(), code.colors());
Source

pub fn as_ref(&self) -> QrCodeRef<'_>

Returns a borrowed QR symbol view with module data and metadata.

Unlike to_colors, this does not allocate or clone the module grid. It is useful for renderers and analyzers that accept a QrSymbol and need version/error-correction metadata in addition to read-only module access.

§Examples
use qrcode_rs::{ModuleSource, QrCode, QrSymbol};

let code = QrCode::new(b"hi").unwrap();
let borrowed = code.as_ref();
assert_eq!(borrowed.version(), code.version());
assert_eq!(borrowed.modules(), code.colors());
Source

pub fn to_colors(&self) -> Vec<Color>

Converts the QR code to a vector of colors.

Source

pub fn into_colors(self) -> Vec<Color>

Converts the QR code to a vector of colors.

Source

pub fn render<P: Pixel>(&self) -> Renderer<'_, P>

Renders the QR code into an image. The result is an image builder, which you may do some additional configuration before copying it into a concrete image. Note: theimage crate itself also provides method to rotate the image, or overlay a logo on top of the QR code.

§Examples

let image = QrCode::new(b"hello").unwrap()
                   .render()
                   .dark_color(Rgb([0, 0, 128]))
                   .light_color(Rgb([224, 224, 224])) // adjust colors
                   .quiet_zone(false)          // disable quiet zone (white border)
                   .min_dimensions(300, 300)   // sets minimum image size
                   .build();
Source

pub fn render_builder<P: Pixel>(&self) -> Renderer<'_, P>

Returns the render builder for this QR code.

This is an explicit builder-style alias for render, useful when code wants the construction and rendering paths to read the same way (QrCode::builder(...).build()?.render_builder::<P>()...).

§Examples
use qrcode_rs::QrCode;

let text = QrCode::new(b"hello").unwrap()
    .render_builder::<char>()
    .dark_color('#')
    .quiet_zone(false)
    .module_dimensions(1, 1)
    .build();

assert!(text.contains('#'));
Source

pub async fn render_async<P>(&self) -> Result<P::Image, JoinError>
where P: Pixel + Send + 'static, P::Image: Send + 'static,

Available on crate feature async only.

Renders the QR code on Tokio’s blocking thread pool.

This opt-in async helper is available with the async feature. It clones the compact module grid and performs the synchronous render work inside tokio::task::spawn_blocking, so callers running inside a Tokio runtime do not execute CPU-heavy rendering on the async worker thread.

§Errors

Returns tokio::task::JoinError if the blocking task is cancelled or panics.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hello").unwrap();
let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
let text = runtime.block_on(code.render_async::<char>()).unwrap();
assert!(!text.is_empty());
Source

pub fn encode_with( registry: &PluginRegistry, encoder_name: &str, input: &[u8], config: &EncodeConfig, ) -> Result<EncodedOutput, PluginError>

Encodes raw input through a named plugin encoder.

This is the encoder-side counterpart to QrCode::render_with: it looks up encoder_name in registry, builds the dynamic encoder with config, and returns the encoder’s type-erased output.

§Errors

Returns PluginError::EncoderNotFound when no encoder is registered with encoder_name, or another PluginError returned by the encoder.

Source

pub fn render_with( &self, registry: &PluginRegistry, renderer_name: &str, config: &RenderConfig, ) -> Result<RenderOutput, PluginError>

Renders the QR code through a named plugin renderer.

The method looks up renderer_name in registry, copies this QR code’s module grid into a mutable ModuleGrid, applies all registered PostProcessor values in registration order, then renders the transformed grid through the selected dynamic renderer.

§Errors

Returns PluginError::RendererNotFound when no renderer is registered with renderer_name, or another PluginError from grid construction, postprocessing, or rendering.

Source

pub fn with_plugins<'a>( &'a self, registry: &'a PluginRegistry, ) -> QrCodePlugins<'a>

Binds this QR code to a plugin registry for fluent plugin rendering.

The returned view borrows both values and delegates to QrCode::render_with, so it has the same deterministic, explicit registry behavior without introducing global plugin state.

Source§

impl QrCode

Source

pub fn builder<D: AsRef<[u8]>>(data: D) -> QrCodeBuilder<D>

Creates a QrCodeBuilder for configuring and constructing a QR code.

This is an ergonomic alternative to the with_* constructors. The builder uses the same encoding paths, so its output is identical to the equivalent constructor.

§Examples
use qrcode_rs::{QrCode, EcLevel};

let code = QrCode::builder(b"https://example.com")
    .ec_level(EcLevel::H)
    .build()
    .unwrap();
Source

pub fn rows(&self) -> Rows<'_>

Returns an iterator yielding one Row of modules at a time.

Each row iterates over the module Colors from left to right. The quiet zone is not included.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hi").unwrap();
for row in code.rows() {
    for color in row {
    }
}
Source

pub fn dark_modules(&self) -> DarkModules<'_>

Returns an iterator over the (x, y) coordinates of every dark module, convenient for custom rendering. The quiet zone is not included.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::new(b"hi").unwrap();
let dark_count = code.dark_modules().count();
Source

pub fn for_url<D: AsRef<[u8]>>(url: D) -> QrResult<Self>

Encodes a URL, using high error correction (robust to print damage).

§Errors

Returns an error only if the URL is too long to encode.

Source

pub fn for_text<D: AsRef<[u8]>>(text: D) -> QrResult<Self>

Encodes plain text at the default (medium) error correction level.

§Errors

Returns an error only if the text is too long to encode.

Source

pub fn for_wifi(ssid: &str, password: &str, auth: &str) -> QrResult<Self>

Encodes a WiFi configuration that most phone cameras will offer to join.

auth is one of WPA, WEP or nopass. Special characters in the SSID/password are backslash-escaped per the WiFi QR specification.

§Errors

Returns an error if the resulting payload is too long to encode.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::for_wifi("MyNetwork", "p\\a;ss", "WPA").unwrap();
Source

pub fn for_vcard(name: &str, phone: &str, email: &str) -> QrResult<Self>

Encodes a minimal vCard 3.0 contact card.

§Errors

Returns an error if the resulting payload is too long to encode.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::for_vcard("John Doe", "+1234567890", "john@example.com").unwrap();
Source

pub fn for_gs1<D: AsRef<[u8]>>(data: D) -> QrResult<Self>

Encodes a GS1 data carrier (FNC1 in first position), e.g. a GTIN / application-identifier payload such as "010491234512345915970331301234561842". Uses medium error correction and the smallest fitting version.

§Errors

Returns an error if the data is too long to encode.

§Examples
use qrcode_rs::QrCode;

let code = QrCode::for_gs1("010491234512345915970331301234561842").unwrap();
Source

pub fn structured_append<D: AsRef<[u8]>>( payload: D, symbols: u8, ec: EcLevel, ) -> QrResult<Vec<Self>>

Splits payload across symbols QR codes (2..=16) using Structured Append (ISO/IEC 18004 §7.4), each at error-correction level ec. Every symbol is the smallest version that fits its chunk plus the 20-bit Structured Append header.

This is a thin convenience over crate::structured_append::StructuredAppend; see that type for the split and parity details, and crate::structured_append::reassemble for recombining decoded symbols.

§Errors

Returns QrError::InvalidStructuredAppend if symbols is not in 2..=16, or QrError::DataTooLong if a chunk cannot fit even version 40 at ec.

§Examples
use qrcode_rs::{EcLevel, QrCode};

let codes = QrCode::structured_append(b"split across multiple symbols", 3, EcLevel::M)?;
assert_eq!(codes.len(), 3);
Source

pub fn alt_text<D: AsRef<[u8]>>(data: D) -> String

Generates accessible alt text describing a QR code that encodes data.

URLs are described as “linking to …”; other payloads as “containing: …”. Use the result as the alt of an <img> or the aria-label of an inline SVG so assistive technology can describe the code without decoding it.

This is an associated function (it does not require a constructed QrCode), so the input data does not need to be retained on the code.

§Examples
use qrcode_rs::QrCode;

assert_eq!(QrCode::alt_text("https://example.com"), "QR code linking to https://example.com");
assert_eq!(QrCode::alt_text("hello"), "QR code containing: hello");
Source

pub fn alt_text_custom<D: AsRef<[u8]>, F: FnOnce(&[u8]) -> String>( data: D, f: F, ) -> String

Generates alt text with a custom formatter that receives the raw bytes.

§Examples
use qrcode_rs::QrCode;

let alt = QrCode::alt_text_custom("hello", |data| {
    format!("A QR code with {} bytes", data.len())
});
assert_eq!(alt, "A QR code with 5 bytes");
Source§

impl QrCode

Source

pub fn to_serializable(&self) -> QrCodeData

Available on crate feature serde only.

Serializes this QR code into a QrCodeData (requires the serde feature).

Source

pub fn from_serializable(data: QrCodeData) -> Self

Available on crate feature serde only.

Reconstructs a QrCode from QrCodeData (requires the serde feature).

data is trusted: content.len() must equal width * width (checked in debug builds). Pair with QrCode::to_serializable.

Trait Implementations§

Source§

impl Clone for QrCode

Source§

fn clone(&self) -> QrCode

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Index<(usize, usize)> for QrCode

Source§

type Output = Color

The returned type after indexing.
Source§

fn index(&self, (x, y): (usize, usize)) -> &Color

Performs the indexing (container[index]) operation. Read more
Source§

impl ModuleStorage for QrCode

Source§

fn get(&self, x: usize, y: usize) -> Color

Returns the color at (x, y). Read more
Source§

fn set(&mut self, x: usize, y: usize, color: Color)

Sets the color at (x, y). Read more
Source§

fn width(&self) -> usize

Returns the number of modules per row.
Source§

fn height(&self) -> usize

Returns the number of module rows.
Source§

fn modules(&self) -> &[Color]

Returns all modules in row-major order.
Source§

fn is_empty(&self) -> bool

Returns whether this storage has no modules.
Source§

impl QrSymbol for QrCode

Source§

fn version(&self) -> Version

Returns the encoded QR or Micro QR version.
Source§

fn error_correction_level(&self) -> EcLevel

Returns the encoded error-correction level.
Source§

fn quiet_zone(&self) -> u32

Returns the default quiet-zone width in modules for this symbol. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ModuleSource for T
where T: ModuleStorage + ?Sized,

Source§

fn get(&self, x: usize, y: usize) -> Color

Returns the color at (x, y). Read more
Source§

fn width(&self) -> usize

Returns the number of modules per row.
Source§

fn height(&self) -> usize

Returns the number of module rows.
Source§

fn modules(&self) -> &[Color]

Returns all modules in row-major order.
Source§

fn is_empty(&self) -> bool

Returns whether this storage has no modules.
Source§

fn row(&self, y: usize) -> &[Color]

Returns row y as a contiguous row-major slice. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.