0
# Core QR Code Generation
1
2
Essential QR code creation functionality that forms the foundation of the qrcode library. This includes the main QRCode class, quick generation functions, data management, and core QR code generation algorithms.
3
4
## Capabilities
5
6
### Quick Generation Function
7
8
The `make` function provides the simplest way to generate QR codes with automatic configuration.
9
10
```python { .api }
11
def make(data=None, **kwargs):
12
"""
13
Create a QR code image directly from data.
14
15
Parameters:
16
- data: The data to encode in the QR code
17
- **kwargs: All QRCode constructor parameters (version, error_correction, etc.)
18
19
Returns:
20
BaseImage: QR code image (type depends on available image libraries)
21
"""
22
```
23
24
**Usage Example:**
25
26
```python
27
import qrcode
28
29
# Generate QR code with default settings
30
img = qrcode.make('Hello World')
31
img.save('hello.png')
32
33
# Generate with custom settings
34
img = qrcode.make('Hello World',
35
version=1,
36
error_correction=qrcode.constants.ERROR_CORRECT_H,
37
box_size=20,
38
border=2)
39
```
40
41
### QRCode Class
42
43
The main QRCode class provides comprehensive control over QR code generation with support for incremental data addition, version optimization, and multiple output formats.
44
45
```python { .api }
46
class QRCode:
47
"""
48
Main QR code generator class.
49
50
Attributes:
51
- version (int): QR code version (1-40, or None for auto-sizing)
52
- error_correction (int): Error correction level constant
53
- box_size (int): Size of each box in pixels
54
- border (int): Border size in boxes
55
- mask_pattern (int or None): Mask pattern (0-7, or None for auto)
56
- image_factory (class or None): Image factory class to use
57
"""
58
59
def __init__(self, version=None, error_correction=constants.ERROR_CORRECT_M,
60
box_size=10, border=4, image_factory=None, mask_pattern=None):
61
"""
62
Initialize QRCode instance.
63
64
Parameters:
65
- version (int or None): QR version 1-40, None for auto-sizing
66
- error_correction (int): Error correction level (constants.ERROR_CORRECT_*)
67
- box_size (int): Pixels per QR code box
68
- border (int): Border thickness in boxes (minimum 4 per spec)
69
- image_factory (class or None): Image factory class
70
- mask_pattern (int or None): Mask pattern 0-7, None for auto
71
"""
72
```
73
74
### Data Management
75
76
Methods for adding data to QR codes and managing the encoding process.
77
78
```python { .api }
79
def add_data(self, data, optimize=20):
80
"""
81
Add data to the QR code.
82
83
Parameters:
84
- data (str or bytes or QRData): Data to encode
85
- optimize (int): Minimum chunk size for optimization (0 to disable)
86
87
Notes:
88
- Can be called multiple times to add more data
89
- Optimization splits data into chunks for better compression
90
"""
91
92
def clear(self):
93
"""
94
Reset the QR code's internal data.
95
96
Clears all added data and resets the QR code to initial state.
97
"""
98
```
99
100
**Usage Example:**
101
102
```python
103
import qrcode
104
105
qr = qrcode.QRCode()
106
107
# Add data incrementally
108
qr.add_data('First part')
109
qr.add_data('Second part')
110
111
# Generate the QR code
112
qr.make(fit=True)
113
img = qr.make_image()
114
```
115
116
### QR Code Generation
117
118
Core methods for compiling data into QR code matrices and generating final output.
119
120
```python { .api }
121
def make(self, fit=True):
122
"""
123
Compile the data into a QR code matrix.
124
125
Parameters:
126
- fit (bool): If True, find optimal version for data size
127
128
Notes:
129
- Must be called before make_image()
130
- Automatically determines version if version=None and fit=True
131
"""
132
133
def make_image(self, image_factory=None, **kwargs):
134
"""
135
Generate QR code image.
136
137
Parameters:
138
- image_factory (class or None): Override default image factory
139
- **kwargs: Arguments passed to image factory
140
141
Returns:
142
BaseImage: Generated QR code image
143
144
Common kwargs:
145
- fill_color: Foreground color
146
- back_color: Background color
147
"""
148
```
149
150
### Version and Size Management
151
152
Methods for determining optimal QR code size and retrieving version information.
153
154
```python { .api }
155
def best_fit(self, start=None):
156
"""
157
Find the minimum QR code version required for the data.
158
159
Parameters:
160
- start (int or None): Starting version to check from
161
162
Returns:
163
int: Optimal QR code version (1-40)
164
165
Raises:
166
DataOverflowError: If data too large for maximum version
167
"""
168
169
@property
170
def version(self):
171
"""
172
Get or set the QR code version.
173
174
Returns:
175
int: Current QR code version (1-40)
176
177
Notes:
178
- Auto-calculated if not explicitly set
179
- Triggers best_fit() when accessed if None
180
"""
181
```
182
183
### Matrix Access
184
185
Methods for accessing the raw QR code data matrix.
186
187
```python { .api }
188
def get_matrix(self):
189
"""
190
Get the QR code as a 2D boolean matrix including border.
191
192
Returns:
193
List[List[bool]]: 2D matrix where True = black module, False = white
194
195
Notes:
196
- Includes border modules
197
- Set border=0 to get matrix without border
198
- Must call make() first
199
"""
200
201
def active_with_neighbors(self, row, col):
202
"""
203
Get module state with neighbor information for advanced drawing.
204
205
Parameters:
206
- row (int): Row index in the matrix
207
- col (int): Column index in the matrix
208
209
Returns:
210
ActiveWithNeighbors: Named tuple with module states
211
212
Notes:
213
- Used by advanced module drawers for context-aware drawing
214
- Provides 3x3 neighborhood information
215
"""
216
```
217
218
**Usage Example:**
219
220
```python
221
import qrcode
222
223
qr = qrcode.QRCode(border=0) # No border for raw matrix
224
qr.add_data('Test data')
225
qr.make()
226
227
# Get raw matrix
228
matrix = qr.get_matrix()
229
print(f"QR code size: {len(matrix)}x{len(matrix[0])}")
230
231
# Print ASCII representation
232
for row in matrix:
233
print(''.join('██' if cell else ' ' for cell in row))
234
```
235
236
## Error Handling
237
238
```python { .api }
239
class DataOverflowError(Exception):
240
"""
241
Raised when data exceeds the maximum capacity of QR code version 40.
242
243
This happens when the data is too large to fit in even the largest
244
QR code format (version 40 with lowest error correction level).
245
"""
246
```
247
248
**Usage Example:**
249
250
```python
251
import qrcode
252
from qrcode.exceptions import DataOverflowError
253
254
try:
255
# Very large data that might not fit
256
large_data = 'x' * 10000
257
qr = qrcode.QRCode()
258
qr.add_data(large_data)
259
qr.make(fit=True)
260
except DataOverflowError:
261
print("Data too large for QR code")
262
# Handle by splitting data or using different approach
263
```