0
# ZXing-C++
1
2
ZXing-C++ ("zebra crossing") is an open-source, multi-format linear/matrix barcode image processing library implemented in C++. Originally ported from the Java ZXing Library, it has evolved into a high-performance C++20 library with significant improvements in runtime and detection performance. It provides comprehensive barcode reading and writing capabilities for a wide variety of formats including QR codes, UPC/EAN codes, DataMatrix, Aztec, PDF417, and many linear barcode formats.
3
4
## Package Information
5
6
- **Package Name**: zxing-cpp
7
- **Package Type**: C++ Library
8
- **Language**: C++20 (C++17 compatible mode available)
9
- **License**: Apache-2.0
10
- **Build System**: CMake 3.16+
11
- **Installation**: Via package managers (vcpkg, conan, system packages) or build from source
12
13
## Core Imports
14
15
For C++ projects using CMake:
16
17
```cpp
18
#include "ZXing/ReadBarcode.h" // Core reading functionality
19
#include "ZXing/WriteBarcode.h" // Experimental writing API
20
#include "ZXing/MultiFormatWriter.h" // Legacy writing API
21
```
22
23
## Basic Usage
24
25
### Reading Barcodes
26
27
```cpp
28
#include "ZXing/ReadBarcode.h"
29
#include <iostream>
30
31
int main() {
32
// Assume image data is loaded from somewhere
33
int width, height;
34
unsigned char* data;
35
36
// Create image view - supports various pixel formats
37
auto image = ZXing::ImageView(data, width, height, ZXing::ImageFormat::Lum);
38
39
// Configure reader options
40
auto options = ZXing::ReaderOptions()
41
.setFormats(ZXing::BarcodeFormat::Any)
42
.setTryHarder(true)
43
.setTryRotate(true);
44
45
// Read single barcode
46
auto result = ZXing::ReadBarcode(image, options);
47
if (result.isValid()) {
48
std::cout << ZXing::ToString(result.format()) << ": "
49
<< result.text() << std::endl;
50
}
51
52
// Read multiple barcodes
53
auto results = ZXing::ReadBarcodes(image, options);
54
for (const auto& barcode : results) {
55
std::cout << ZXing::ToString(barcode.format()) << ": "
56
<< barcode.text() << std::endl;
57
}
58
59
return 0;
60
}
61
```
62
63
### Writing Barcodes (Legacy API)
64
65
```cpp
66
#include "ZXing/MultiFormatWriter.h"
67
#include "ZXing/BitMatrix.h"
68
69
// Create writer for specific format
70
auto writer = ZXing::MultiFormatWriter(ZXing::BarcodeFormat::QRCode)
71
.setEncoding(ZXing::CharacterSet::UTF8)
72
.setEccLevel(4)
73
.setMargin(10);
74
75
// Generate barcode as bit matrix
76
auto matrix = writer.encode("Hello, World!", 300, 300);
77
78
// Convert to your preferred image format
79
// (matrix provides boolean values for each pixel)
80
```
81
82
## Architecture
83
84
ZXing-C++ is designed around several key components:
85
86
- **Image Processing**: `ImageView` class for zero-copy image data handling with multiple pixel format support
87
- **Format Detection**: Automatic format detection or explicit format specification via `BarcodeFormat` enumeration
88
- **Reader Pipeline**: Configurable reading pipeline with `ReaderOptions` for performance vs accuracy trade-offs
89
- **Writer APIs**: Both legacy (`MultiFormatWriter`) and experimental (`WriteBarcode`) APIs for barcode generation
90
- **Type System**: Strong typing with comprehensive enum classes and structured result objects
91
- **Error Handling**: Detailed error reporting through `Error` class with categorized error types
92
- **Thread Safety**: Thread-safe reading operations with no shared state
93
94
## Capabilities
95
96
### Barcode Reading
97
98
Core barcode detection and decoding functionality supporting over 20 barcode formats. Provides configurable accuracy vs performance trade-offs and comprehensive result metadata.
99
100
```cpp { .api }
101
ZXing::Barcode ReadBarcode(const ImageView& image, const ReaderOptions& options = {});
102
ZXing::Barcodes ReadBarcodes(const ImageView& image, const ReaderOptions& options = {});
103
```
104
105
[Barcode Reading](./reading.md)
106
107
### Image Processing
108
109
Image data handling and format conversion utilities. Supports multiple pixel formats, image transformations, and memory-efficient processing.
110
111
```cpp { .api }
112
class ImageView {
113
ImageView() = default;
114
ImageView(const uint8_t* data, int width, int height, ImageFormat format,
115
int rowStride = 0, int pixStride = 0);
116
ImageView(const uint8_t* data, int size, int width, int height, ImageFormat format,
117
int rowStride = 0, int pixStride = 0);
118
119
int width() const;
120
int height() const;
121
int pixStride() const;
122
int rowStride() const;
123
ImageFormat format() const;
124
125
const uint8_t* data() const;
126
const uint8_t* data(int x, int y) const;
127
128
ImageView cropped(int left, int top, int width, int height) const;
129
ImageView rotated(int degree) const;
130
ImageView subsampled(int scale) const;
131
};
132
133
class Image : public ImageView {
134
Image() = default;
135
Image(int w, int h, ImageFormat f = ImageFormat::Lum);
136
};
137
```
138
139
[Image Processing](./image-processing.md)
140
141
### Configuration and Options
142
143
Comprehensive configuration system for optimizing barcode detection for specific use cases and image characteristics.
144
145
```cpp { .api }
146
class ReaderOptions {
147
ReaderOptions();
148
149
// Format selection
150
ReaderOptions& setFormats(BarcodeFormats formats);
151
BarcodeFormats formats() const noexcept;
152
153
// Performance vs accuracy trade-offs
154
ReaderOptions& setTryHarder(bool tryHarder);
155
ReaderOptions& setTryRotate(bool tryRotate);
156
ReaderOptions& setTryInvert(bool tryInvert);
157
ReaderOptions& setTryDownscale(bool tryDownscale);
158
159
// Binarization
160
ReaderOptions& setBinarizer(Binarizer binarizer);
161
Binarizer binarizer() const noexcept;
162
163
// Image characteristics
164
ReaderOptions& setIsPure(bool isPure);
165
ReaderOptions& setDownscaleThreshold(uint16_t threshold);
166
ReaderOptions& setDownscaleFactor(uint8_t factor);
167
168
// Result filtering
169
ReaderOptions& setMinLineCount(uint8_t count);
170
ReaderOptions& setMaxNumberOfSymbols(uint8_t max);
171
ReaderOptions& setReturnErrors(bool returnErrors);
172
173
// Text processing
174
ReaderOptions& setTextMode(TextMode mode);
175
ReaderOptions& setCharacterSet(CharacterSet charset);
176
ReaderOptions& setCharacterSet(std::string_view charset);
177
178
// Format-specific options
179
ReaderOptions& setTryCode39ExtendedMode(bool tryExtended);
180
ReaderOptions& setEanAddOnSymbol(EanAddOnSymbol mode);
181
182
bool hasFormat(BarcodeFormats f) const noexcept;
183
};
184
```
185
186
[Configuration](./configuration.md)
187
188
### Legacy Barcode Writing
189
190
Established barcode generation API supporting the most common barcode formats with basic customization options.
191
192
```cpp { .api }
193
class MultiFormatWriter {
194
explicit MultiFormatWriter(BarcodeFormat format);
195
196
MultiFormatWriter& setEncoding(CharacterSet encoding);
197
MultiFormatWriter& setEccLevel(int level);
198
MultiFormatWriter& setMargin(int margin);
199
200
BitMatrix encode(const std::string& contents, int width, int height) const;
201
BitMatrix encode(const std::wstring& contents, int width, int height) const;
202
};
203
```
204
205
[Legacy Writing](./legacy-writing.md)
206
207
### Experimental Barcode Writing
208
209
Advanced barcode generation API with extended format support and multiple output formats including SVG, UTF-8 text, and bitmap images.
210
211
```cpp { .api }
212
class CreatorOptions {
213
CreatorOptions(BarcodeFormat format);
214
~CreatorOptions();
215
CreatorOptions(CreatorOptions&&);
216
CreatorOptions& operator=(CreatorOptions&&);
217
218
CreatorOptions& format(BarcodeFormat f);
219
CreatorOptions& readerInit(bool v);
220
CreatorOptions& forceSquareDataMatrix(bool v);
221
CreatorOptions& ecLevel(std::string level);
222
};
223
224
class WriterOptions {
225
WriterOptions();
226
~WriterOptions();
227
WriterOptions(WriterOptions&&);
228
WriterOptions& operator=(WriterOptions&&);
229
230
WriterOptions& scale(int scale);
231
WriterOptions& sizeHint(int hint);
232
WriterOptions& rotate(int degrees);
233
WriterOptions& withHRT(bool hrt);
234
WriterOptions& withQuietZones(bool quiet);
235
};
236
237
Barcode CreateBarcodeFromText(std::string_view contents, const CreatorOptions& options);
238
Barcode CreateBarcodeFromBytes(const void* data, int size, const CreatorOptions& options);
239
240
std::string WriteBarcodeToSVG(const Barcode& barcode, const WriterOptions& options = {});
241
std::string WriteBarcodeToUtf8(const Barcode& barcode, const WriterOptions& options = {});
242
Image WriteBarcodeToImage(const Barcode& barcode, const WriterOptions& options = {});
243
```
244
245
[Experimental Writing](./experimental-writing.md)
246
247
### Result Processing
248
249
Comprehensive result analysis and metadata extraction from decoded barcodes, including structured append sequence handling and error analysis.
250
251
```cpp { .api }
252
class Result {
253
Result() = default;
254
Result(const std::string& text, int y, int xStart, int xStop,
255
BarcodeFormat format, SymbologyIdentifier si, Error error = {},
256
bool readerInit = false);
257
258
bool isValid() const;
259
BarcodeFormat format() const;
260
261
const ByteArray& bytes() const;
262
ByteArray bytesECI() const;
263
std::string text(TextMode mode) const;
264
std::string text() const;
265
266
std::string ecLevel() const;
267
ContentType contentType() const;
268
bool hasECI() const;
269
270
const Position& position() const;
271
void setPosition(Position pos);
272
int orientation() const;
273
274
bool isMirrored() const;
275
bool isInverted() const;
276
277
std::string symbologyIdentifier() const;
278
279
int sequenceSize() const;
280
int sequenceIndex() const;
281
std::string sequenceId() const;
282
bool isLastInSequence() const;
283
bool isPartOfSequence() const;
284
285
bool readerInit() const;
286
int lineCount() const;
287
std::string version() const;
288
289
const Error& error() const;
290
291
bool operator==(const Result& other) const;
292
};
293
294
Barcode MergeStructuredAppendSequence(const Barcodes& results);
295
Barcodes MergeStructuredAppendSequences(const Barcodes& barcodes);
296
```
297
298
[Result Processing](./result-processing.md)
299
300
## Supported Formats
301
302
ZXing-C++ supports the following barcode formats:
303
304
**Linear/1D Formats:**
305
- UPC-A, UPC-E
306
- EAN-8, EAN-13
307
- Code 39, Code 93, Code 128
308
- Codabar
309
- ITF (Interleaved Two of Five)
310
- DataBar (RSS), DataBar Expanded, DataBar Limited
311
- DX Film Edge
312
313
**Matrix/2D Formats:**
314
- QR Code, Micro QR Code, rMQR Code
315
- DataMatrix
316
- Aztec
317
- PDF417
318
- MaxiCode (partial support)
319
320
## Types
321
322
```cpp { .api }
323
enum class BarcodeFormat {
324
None, Aztec, Codabar, Code39, Code93, Code128, DataBar, DataBarExpanded,
325
DataMatrix, EAN8, EAN13, ITF, MaxiCode, PDF417, QRCode, UPCA, UPCE,
326
MicroQRCode, RMQRCode, DXFilmEdge, DataBarLimited,
327
328
LinearCodes = Codabar | Code39 | Code93 | Code128 | EAN8 | EAN13 | ITF |
329
DataBar | DataBarExpanded | DataBarLimited | DXFilmEdge | UPCA | UPCE,
330
MatrixCodes = Aztec | DataMatrix | MaxiCode | PDF417 | QRCode | MicroQRCode | RMQRCode,
331
Any = LinearCodes | MatrixCodes
332
};
333
334
enum class ImageFormat : uint32_t {
335
None, Lum, LumA, RGB, BGR, RGBA, ARGB, BGRA, ABGR
336
};
337
338
enum class TextMode : unsigned char {
339
Plain, ECI, HRI, Hex, Escaped
340
};
341
342
enum class Binarizer : unsigned char {
343
LocalAverage, GlobalHistogram, FixedThreshold, BoolCast
344
};
345
346
enum class EanAddOnSymbol : unsigned char {
347
Ignore, Read, Require
348
};
349
350
enum class ContentType {
351
Text, Binary, Mixed, GS1, ISO15434, UnknownECI
352
};
353
354
enum class CharacterSet : unsigned char {
355
Unknown, ASCII, ISO8859_1, ISO8859_2, ISO8859_3, ISO8859_4, ISO8859_5,
356
ISO8859_6, ISO8859_7, ISO8859_8, ISO8859_9, ISO8859_10, ISO8859_11,
357
ISO8859_13, ISO8859_14, ISO8859_15, ISO8859_16, Cp437, Cp1250, Cp1251,
358
Cp1252, Cp1256, Shift_JIS, Big5, GB2312, GB18030, EUC_JP, EUC_KR,
359
UTF16BE, UTF8, UTF16LE, UTF32BE, UTF32LE
360
};
361
362
class Error {
363
enum class Type : uint8_t { None, Format, Checksum, Unsupported };
364
365
Error() = default;
366
Error(Type type, std::string msg = {});
367
368
Type type() const noexcept;
369
const std::string& msg() const noexcept;
370
std::string location() const;
371
explicit operator bool() const noexcept;
372
373
bool operator==(const Error& other) const noexcept;
374
bool operator!=(const Error& other) const noexcept;
375
376
static constexpr auto Format = Type::Format;
377
static constexpr auto Checksum = Type::Checksum;
378
static constexpr auto Unsupported = Type::Unsupported;
379
};
380
381
class ByteArray : public std::vector<uint8_t> {
382
ByteArray() = default;
383
ByteArray(std::initializer_list<uint8_t> list);
384
explicit ByteArray(int len);
385
explicit ByteArray(const std::string& str);
386
387
void append(const ByteArray& other);
388
std::string_view asString(size_t pos = 0, size_t len = std::string_view::npos) const;
389
};
390
391
class BitMatrix {
392
BitMatrix() = default;
393
BitMatrix(int width, int height);
394
explicit BitMatrix(int dimension);
395
396
int width() const;
397
int height() const;
398
bool get(int x, int y) const;
399
void set(int x, int y, bool val = true);
400
void flip(int x, int y);
401
void flipAll();
402
403
BitMatrix copy() const;
404
};
405
406
template <typename T>
407
class Quadrilateral : public std::array<T, 4> {
408
using Point = T;
409
410
Quadrilateral() = default;
411
Quadrilateral(T tl, T tr, T br, T bl);
412
413
constexpr Point topLeft() const noexcept;
414
constexpr Point topRight() const noexcept;
415
constexpr Point bottomRight() const noexcept;
416
constexpr Point bottomLeft() const noexcept;
417
418
double orientation() const;
419
};
420
421
struct SymbologyIdentifier {
422
char code = 0;
423
char modifier = 0;
424
char eciModifierOffset = 0;
425
426
std::string toString(bool hasECI = false) const;
427
};
428
429
// Utility Functions
430
std::string ToString(BarcodeFormat format);
431
std::string ToString(BarcodeFormats formats);
432
std::string ToString(ContentType type);
433
std::string ToString(const Error& e);
434
435
BarcodeFormat BarcodeFormatFromString(std::string_view str);
436
BarcodeFormats BarcodeFormatsFromString(std::string_view str);
437
CharacterSet CharacterSetFromString(std::string_view str);
438
439
std::string ToHex(const ByteArray& bytes);
440
441
// Type Aliases
442
using Position = QuadrilateralI;
443
using QuadrilateralF = Quadrilateral<PointF>;
444
using QuadrilateralI = Quadrilateral<PointI>;
445
using Barcode = Result;
446
using Barcodes = std::vector<Barcode>;
447
using BarcodeFormats = Flags<BarcodeFormat>;
448
```