qrcode-generator 6.1.1

Generates ISO/IEC 18004 QR Code and Micro QR Code symbols and ISO/IEC 23941 rMQR symbols in pure Rust, then renders them as grayscale, PNG and SVG images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*!
# QR Code Generator

This crate generates ISO/IEC 18004 QR Code and Micro QR Code symbols and ISO/IEC 23941 rMQR symbols in pure Rust, then renders them as grayscale, PNG and SVG images.

You give it data and get back a ready-to-scan image. The text encoders automatically choose the shortest Numeric, Alphanumeric, Byte and optional Kanji segmentation for each candidate version, and the Model 2 and rMQR encoders also optimize ECI transitions.

## Quick start

Encode text and read the raw module grid:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection};

let symbol = Encoder::new(ErrorCorrection::Medium)
    .encode_text("Hello, world!")
    .unwrap();

// `true` is a dark module and `false` is a light module.
let matrix: Vec<Vec<bool>> = symbol.to_matrix();

println!("{} modules per side", symbol.size());
# }
```

Or render straight to image files:

```rust,no_run
# #[cfg(all(feature = "std", feature = "qr", feature = "image"))] {
use qrcode_generator::{Renderer, qr::{Encoder, ErrorCorrection}};

let symbol = Encoder::new(ErrorCorrection::Medium)
    .encode_text("Hello, world!")
    .unwrap();

Renderer::new(&symbol, 512).save_svg("hello.svg", None::<&str>).unwrap();
Renderer::new(&symbol, 512).save_png("hello.png").unwrap();
# }
```

## Encode, then render

Every workflow has two steps. An `Encoder` (from the `qr`, `micro` or `rmqr` module) turns your data into a `Symbol`, the abstract grid of modules. A `Renderer` then turns that `Symbol` into a concrete output such as an SVG string, a PNG file or a grayscale buffer. The same `Symbol` can be rendered many times at different sizes.

## Key terms

A few QR Code words appear throughout this documentation:

- **Module** — the smallest square of a QR Code, the equivalent of one pixel. A dark module is `true` in the matrix.
- **Matrix** — the full grid of modules. `Symbol::to_matrix` returns it as `Vec<Vec<bool>>`, and `Symbol::modules` exposes it as one flat row-major slice without copying.
- **Symbol** — one complete QR Code, Micro QR Code or rMQR symbol.
- **Version** — the symbol size. QR Code versions run from 1 (21×21 modules) to 40 (177×177), Micro QR Code has versions M1 to M4 (11×11 to 17×17), and rMQR has 32 rectangular sizes.
- **Error correction level** — how much redundancy is added so a dirty or partly hidden symbol still scans. The Low, Medium, Quartile and High levels recover roughly 7%, 15%, 25% and 30% of the codewords, and a higher level is more robust but leaves less room for your own data. Micro QR Code version M1 instead uses a detection-only level that finds errors without correcting them.
- **Mask** — a regular pattern applied over the data to avoid layouts that confuse scanners. The best mask is chosen automatically, so you rarely set it yourself.
- **Quiet zone** — the plain margin around the symbol that scanners need. It defaults to 4 modules for QR Code and 2 for Micro QR Code and rMQR.
- **Mode / segment** — how characters are packed. Numeric is the most compact, then Alphanumeric, then Byte, plus optional Kanji, and the encoder mixes them automatically to save space.
- **ECI** — an Extended Channel Interpretation header that declares the character set, such as UTF-8, when it is not the default ISO-8859-1.

## Encoding

`encode_text` interprets the input as ISO-8859-1 when possible and adds a UTF-8 ECI header only when it is needed. The C1 control characters U+0080 to U+009F are not in the byte table of ISO/IEC 18004, so they use UTF-8 as well:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection};

let symbol = Encoder::new(ErrorCorrection::Medium)
    .encode_text("café ☕")
    .unwrap();
# let _ = symbol;
# }
```

`encode_bytes` stores an exact binary payload and never guesses a character set:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection};

let symbol = Encoder::new(ErrorCorrection::Quartile)
    .encode_bytes(b"raw\0bytes")
    .unwrap();
# let _ = symbol;
# }
```

The encoder is configured with a builder. You can restrict the versions it may use, or force a specific mask:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection, Version};

let symbol = Encoder::new(ErrorCorrection::Low)
    .version_range(Version::new(1).unwrap()..=Version::new(10).unwrap())
    .encode_text("HELLO")
    .unwrap();
# let _ = symbol;
# }
```

By default the encoder upgrades the error correction level for free when the chosen version has spare room. Call `boost_error_correction(false)` to keep the exact level you requested.

### Explicit segments

Automatic segmentation is optimal for most inputs, but you can also build `Segment` values yourself and keep their boundaries:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::{Segment, qr::{Encoder, ErrorCorrection}};

let segments = [
    Segment::numeric("1234567").unwrap(),
    Segment::alphanumeric("ABCDEFG").unwrap(),
];

let symbol = Encoder::new(ErrorCorrection::Low)
    .encode_segments(&segments)
    .unwrap();
# let _ = symbol;
# }
```

### Custom text

[`ToQRText`] lets a structured value choose a shorter equivalent spelling before the optimizer runs:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::{ToQRText, qr::{Encoder, ErrorCorrection}};

struct ProductCode(&'static str);

impl ToQRText for ProductCode {
    fn to_qr_text(&self) -> String {
        self.0.to_ascii_uppercase()
    }
}

let symbol = Encoder::new(ErrorCorrection::Medium)
    .encode_to_qr_text(&ProductCode("item-123"))
    .unwrap();
# let _ = symbol;
# }
```

The value must keep its meaning. With the optional `url` feature, `url::Url` implements `ToQRText` by normalizing case-insensitive URL parts and percent escapes:

```rust
# #[cfg(all(feature = "qr", feature = "url"))] {
use qrcode_generator::qr::{Encoder, ErrorCorrection};
use url::Url;

let url = Url::parse("https://magiclen.org").unwrap();
let symbol = Encoder::new(ErrorCorrection::Medium).encode_to_qr_text(&url).unwrap();
# let _ = symbol;
# }
```

## Rendering

A `Renderer` draws a `Symbol` at exact pixel dimensions. `Renderer::new` keeps the square interface, while `Renderer::new_with_dimensions` accepts a separate width and height for rectangular symbols. In-memory grayscale and SVG output work with `no_std + alloc` and need no extra feature:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::{Renderer, qr::{Encoder, ErrorCorrection}};

let symbol = Encoder::new(ErrorCorrection::Low).encode_text("Hello").unwrap();

let svg: String = Renderer::new(&symbol, 512)
    .svg_xml_declaration(false)
    .to_svg_string(None::<&str>)
    .unwrap();
let pixels: Vec<u8> = Renderer::new(&symbol, 512).to_luma8().unwrap();
# let _ = (svg, pixels);
# }
```

SVG output includes an XML declaration by default. Use `svg_xml_declaration(false)` to start the output with `<svg>` instead. This setting applies to strings, writers and saved files, including async output.

The renderer also implements `Display`, drawing the symbol as compact Unicode text that packs two module rows into every line through half block characters, including the quiet zone. The default form draws dark modules as visible blocks; the alternate form (`{:#}`) draws light modules instead, which keeps the standard contrast on dark terminal backgrounds. Text output works in module units, so the pixel size passed to the renderer does not affect it:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::{Renderer, qr::{Encoder, ErrorCorrection}};

let symbol = Encoder::new(ErrorCorrection::Low).encode_text("Hello").unwrap();
let renderer = Renderer::new(&symbol, 0);

// For light terminal backgrounds.
print!("{renderer}");

// For dark terminal backgrounds.
print!("{renderer:#}");
# }
```

PNG and `ImageBuffer` output need the default `image` feature:

```rust,no_run
# #[cfg(all(feature = "std", feature = "qr", feature = "image"))] {
use qrcode_generator::{Renderer, qr::{Encoder, ErrorCorrection}};

let symbol = Encoder::new(ErrorCorrection::Low).encode_text("Hello").unwrap();

let png: Vec<u8> = Renderer::new(&symbol, 512).to_png_vec().unwrap();

Renderer::new(&symbol, 512).save_png("hello.png").unwrap();
# let _ = png;
# }
```

The default `std` feature adds synchronous writer and file output. File output through `save_svg` and `save_png` is written atomically, so an existing file is left untouched if rendering fails. The requested size is exact: modules are scaled by the largest whole number that fits, and any pixels left over widen the quiet zone evenly. Use `quiet_zone` to change the margin, down to zero if you want.

## Async writing

The optional `tokio` feature adds `write_svg_async` and, with the `image` feature, `write_png_async`, which write and flush to any `tokio::io::AsyncWrite`, including a `tokio::fs::File`. Rendering stays synchronous; only writing and flushing are asynchronous:

```rust,no_run
# #[cfg(all(feature = "qr", feature = "tokio"))]
# mod example {
use qrcode_generator::{
    RenderError, Renderer,
    qr::{Encoder, ErrorCorrection},
};

async fn write<W: tokio::io::AsyncWrite + Unpin>(writer: W) -> Result<(), RenderError> {
    let symbol = Encoder::new(ErrorCorrection::Low).encode_text("Hello").unwrap();

    Renderer::new(&symbol, 512).write_svg_async(writer, None::<&str>).await
}
# }
```

The feature also adds `save_svg_async` and `save_png_async`, which save to a path atomically like their synchronous counterparts by running the write on tokio's blocking pool.

## Micro QR Code

The optional `micro-qr` feature adds an independent encoder for the four Micro QR Code versions, which are smaller than QR Code and suit short payloads:

```rust
# #[cfg(feature = "micro-qr")] {
use qrcode_generator::micro::{Encoder, ErrorCorrection, Version};

let symbol = Encoder::new(ErrorCorrection::Low)
    .version(Version::M2)
    .encode_text("12345")
    .unwrap();
# let _ = symbol;
# }
```

Version M1 supports only the `DetectionOnly` error correction level, which detects errors without correcting them; M2 and M3 add Low and Medium, and M4 also offers Quartile.

Micro QR Code does not support ECI, FNC1 or Structured Append. Its text API accepts ISO-8859-1 except the C1 control characters and, with the `kanji` feature, eligible Shift JIS Kanji characters. Because Micro QR Code has no ECI, a symbol that uses Kanji mode cannot also hold the bytes E0 to EB (à to ë).

## Rectangular Micro QR Code

The optional `rmqr` feature adds all 32 ISO/IEC 23941 rMQR versions. The encoder automatically selects the smallest-area version that fits and performs exact segment and ECI optimization for each character-count profile:

```rust
# #[cfg(feature = "rmqr")] {
use qrcode_generator::{Renderer, rmqr::{Encoder, ErrorCorrection}};

let symbol = Encoder::new(ErrorCorrection::Medium)
    .encode_text("https://magiclen.org")
    .unwrap();

let width = (symbol.width() + 4) * 8;
let height = (symbol.height() + 4) * 8;
let svg = Renderer::new_with_dimensions(&symbol, width, height)
    .to_svg_string(None::<&str>)
    .unwrap();
# }
```

rMQR supports Medium and High error correction, ECI, FNC1 and optional Kanji mode. It has one fixed data mask and does not support Structured Append.

## Automatic family selection

With both `qr` and `micro-qr` enabled, `AutoEncoder` tries the Micro QR Code encoder first and falls back to the Model 2 encoder when the data does not fit, giving you the smallest symbol that works:

```rust
# #[cfg(all(feature = "qr", feature = "micro-qr"))] {
use qrcode_generator::{AutoEncoder, micro, qr};

let encoder = AutoEncoder::new(
    qr::Encoder::new(qr::ErrorCorrection::Medium),
    micro::Encoder::new(micro::ErrorCorrection::Medium),
);

let symbol = encoder.encode_text("HELLO 123").unwrap();
# let _ = symbol;
# }
```

If the Model 2 encoder has FNC1 enabled, `AutoEncoder` uses it directly because Micro QR Code cannot carry FNC1.

## FNC1 and Structured Append

These two QR Code features serve data-exchange standards rather than plain text.

*FNC1* marks a symbol as following a formatted-data standard rather than plain text. First position selects GS1, whose element strings concatenate application identifiers and separate variable-length ones with a `0x1D` (GS) byte; second position selects an industry application indicator through `ApplicationIndicator`. Pass the data with the `0x1D` separators already in place and turn FNC1 on with `qr::Encoder::fnc1`:

```rust
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection, Fnc1};

// AI 01 is a GTIN, the 0x1D (GS) byte separates it, then AI 10 is a batch number.
let symbol = Encoder::new(ErrorCorrection::Medium)
    .fnc1(Some(Fnc1::Gs1))
    .encode_bytes(b"0101234567890128\x1D10ABC")
    .unwrap();
# let _ = symbol;
# }
```

Alphanumeric mode has no value for `0x1D`, so the encoder writes a separator as `%` and doubles a literal `%` to `%%`. It also starts a new segment when a separator is followed by another separator or by a literal `%`, because a reader would otherwise pair those two characters into one literal `%`. Byte mode stores both characters unchanged.

*Structured Append* spreads one message across up to 16 symbols that a reader stitches back together. You can supply the parts yourself, or let the encoder split a message automatically:

```rust,no_run
# #[cfg(feature = "qr")] {
use qrcode_generator::qr::{Encoder, ErrorCorrection};

let symbols = Encoder::new(ErrorCorrection::Medium)
    .encode_text_with_structured_append("a very long message …")
    .unwrap();

println!("{} symbols", symbols.len());
# }
```

Automatic splitting first minimizes the number of symbols, then their largest version, and finally the total symbol area. A reader joins the parts into one data stream, so the text encoders declare an ECI only from the part that first needs it, repeat it at the start of every later part, and use Kanji mode without an ECI header only in a sequence that has no ECI header at all.

With `encode_structured_append_segments`, each part must include its own ECI headers before the data that needs them; ECI state is not copied from earlier parts.

## Kanji

The optional `kanji` feature adds full Shift JIS support to automatic text segmentation and exposes `Segment::kanji`. Eligible characters use the compact 13-bit Kanji mode, and other Shift JIS text such as half-width katakana can be stored as Shift JIS bytes behind an ECI 000020 header. ISO/IEC 18004 reads data before the first ECI header with the default ISO-8859-1 interpretation, so Kanji mode without an ECI header is only used in a symbol that has no ECI header at all, and that symbol keeps its bytes clear of E0 to EB, which readers could take for Shift JIS lead bytes. Any other symbol declares an explicit Shift JIS ECI before its Kanji data. The feature is off by default for the widest scanner compatibility.

Text must keep its original characters after decoding, so Shift JIS follows the character sets that ISO/IEC 18004 names for ECI 000020: JIS X 0208 for two-byte characters and JIS8 for single bytes, where byte 5C is the yen sign and byte 7E is the overline. ISO/IEC 18004 defines no Unicode mapping, and published mappings disagree on eight JIS X 0208 positions. For example, 0x817C reads as U+2212 (minus sign) in JIS-based tables and as U+FF0D (fullwidth hyphen-minus) in Windows-based tables, so neither character uses it. Characters outside JIS X 0208, such as the NEC and IBM extensions ① and 髙, are not used either. QR Code and rMQR store these characters as UTF-8, while Micro QR Code and `Segment::kanji` reject them.

## Cargo features

- `std` (default) enables synchronous writer and file output.
- `qr` (default) enables the Model 2 QR Code encoder.
- `image` (default, requires `std`) enables PNG and `ImageBuffer` output.
- `micro-qr` enables the Micro QR Code encoder with all four versions.
- `rmqr` enables the Rectangular Micro QR Code encoder with all 32 versions.
- `kanji` enables Shift JIS Kanji segments and automatic Kanji mode selection.
- `url` implements `ToQRText` for `url::Url` and works with `no_std + alloc`.
- `tokio` (requires `std`) enables the tokio asynchronous writer and atomic file-save methods.
*/

#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate alloc;
#[cfg(test)]
extern crate std;

mod encode;
mod error;
#[cfg(any(feature = "qr", feature = "micro-qr", feature = "rmqr"))]
mod render;
#[cfg(feature = "url")]
mod url;

#[cfg(all(feature = "qr", feature = "micro-qr"))]
pub use encode::AutoEncoder;
pub use encode::{Segment, ToQRText};
#[cfg(any(feature = "qr", feature = "micro-qr", feature = "rmqr"))]
pub use encode::{Symbol, SymbolErrorCorrection, SymbolVersion};
pub use error::{EncodeError, RenderError};
#[cfg(any(feature = "qr", feature = "micro-qr", feature = "rmqr"))]
pub use render::Renderer;

/// Model 2 QR Code encoding types.
#[cfg(feature = "qr")]
pub mod qr {
    pub use crate::encode::{
        ApplicationIndicator, EciAssignment, Fnc1, QrEncoder as Encoder,
        QrErrorCorrection as ErrorCorrection, QrMask as Mask, QrVersion as Version,
        StructuredAppendInfo,
    };
}

/// Micro QR Code encoding types.
#[cfg(feature = "micro-qr")]
pub mod micro {
    pub use crate::encode::{
        MicroEncoder as Encoder, MicroErrorCorrection as ErrorCorrection, MicroMask as Mask,
        MicroVersion as Version,
    };
}

/// Rectangular Micro QR Code encoding types.
#[cfg(feature = "rmqr")]
pub mod rmqr {
    pub use crate::encode::{
        ApplicationIndicator, EciAssignment, Fnc1, RmqrEncoder as Encoder,
        RmqrErrorCorrection as ErrorCorrection, RmqrVersion as Version,
    };
}