QR Code image generator with customizable image formats, error correction levels, and styling options
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.
The make function provides the simplest way to generate QR codes with automatic configuration.
def make(data=None, **kwargs):
"""
Create a QR code image directly from data.
Parameters:
- data: The data to encode in the QR code
- **kwargs: All QRCode constructor parameters (version, error_correction, etc.)
Returns:
BaseImage: QR code image (type depends on available image libraries)
"""Usage Example:
import qrcode
# Generate QR code with default settings
img = qrcode.make('Hello World')
img.save('hello.png')
# Generate with custom settings
img = qrcode.make('Hello World',
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=20,
border=2)The main QRCode class provides comprehensive control over QR code generation with support for incremental data addition, version optimization, and multiple output formats.
class QRCode:
"""
Main QR code generator class.
Attributes:
- version (int): QR code version (1-40, or None for auto-sizing)
- error_correction (int): Error correction level constant
- box_size (int): Size of each box in pixels
- border (int): Border size in boxes
- mask_pattern (int or None): Mask pattern (0-7, or None for auto)
- image_factory (class or None): Image factory class to use
"""
def __init__(self, version=None, error_correction=constants.ERROR_CORRECT_M,
box_size=10, border=4, image_factory=None, mask_pattern=None):
"""
Initialize QRCode instance.
Parameters:
- version (int or None): QR version 1-40, None for auto-sizing
- error_correction (int): Error correction level (constants.ERROR_CORRECT_*)
- box_size (int): Pixels per QR code box
- border (int): Border thickness in boxes (minimum 4 per spec)
- image_factory (class or None): Image factory class
- mask_pattern (int or None): Mask pattern 0-7, None for auto
"""Methods for adding data to QR codes and managing the encoding process.
def add_data(self, data, optimize=20):
"""
Add data to the QR code.
Parameters:
- data (str or bytes or QRData): Data to encode
- optimize (int): Minimum chunk size for optimization (0 to disable)
Notes:
- Can be called multiple times to add more data
- Optimization splits data into chunks for better compression
"""
def clear(self):
"""
Reset the QR code's internal data.
Clears all added data and resets the QR code to initial state.
"""Usage Example:
import qrcode
qr = qrcode.QRCode()
# Add data incrementally
qr.add_data('First part')
qr.add_data('Second part')
# Generate the QR code
qr.make(fit=True)
img = qr.make_image()Core methods for compiling data into QR code matrices and generating final output.
def make(self, fit=True):
"""
Compile the data into a QR code matrix.
Parameters:
- fit (bool): If True, find optimal version for data size
Notes:
- Must be called before make_image()
- Automatically determines version if version=None and fit=True
"""
def make_image(self, image_factory=None, **kwargs):
"""
Generate QR code image.
Parameters:
- image_factory (class or None): Override default image factory
- **kwargs: Arguments passed to image factory
Returns:
BaseImage: Generated QR code image
Common kwargs:
- fill_color: Foreground color
- back_color: Background color
"""Methods for determining optimal QR code size and retrieving version information.
def best_fit(self, start=None):
"""
Find the minimum QR code version required for the data.
Parameters:
- start (int or None): Starting version to check from
Returns:
int: Optimal QR code version (1-40)
Raises:
DataOverflowError: If data too large for maximum version
"""
@property
def version(self):
"""
Get or set the QR code version.
Returns:
int: Current QR code version (1-40)
Notes:
- Auto-calculated if not explicitly set
- Triggers best_fit() when accessed if None
"""Methods for accessing the raw QR code data matrix.
def get_matrix(self):
"""
Get the QR code as a 2D boolean matrix including border.
Returns:
List[List[bool]]: 2D matrix where True = black module, False = white
Notes:
- Includes border modules
- Set border=0 to get matrix without border
- Must call make() first
"""
def active_with_neighbors(self, row, col):
"""
Get module state with neighbor information for advanced drawing.
Parameters:
- row (int): Row index in the matrix
- col (int): Column index in the matrix
Returns:
ActiveWithNeighbors: Named tuple with module states
Notes:
- Used by advanced module drawers for context-aware drawing
- Provides 3x3 neighborhood information
"""Usage Example:
import qrcode
qr = qrcode.QRCode(border=0) # No border for raw matrix
qr.add_data('Test data')
qr.make()
# Get raw matrix
matrix = qr.get_matrix()
print(f"QR code size: {len(matrix)}x{len(matrix[0])}")
# Print ASCII representation
for row in matrix:
print(''.join('██' if cell else ' ' for cell in row))class DataOverflowError(Exception):
"""
Raised when data exceeds the maximum capacity of QR code version 40.
This happens when the data is too large to fit in even the largest
QR code format (version 40 with lowest error correction level).
"""Usage Example:
import qrcode
from qrcode.exceptions import DataOverflowError
try:
# Very large data that might not fit
large_data = 'x' * 10000
qr = qrcode.QRCode()
qr.add_data(large_data)
qr.make(fit=True)
except DataOverflowError:
print("Data too large for QR code")
# Handle by splitting data or using different approachevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10