zxing-cpp Python Bindings

3.0.0 · active · verified Thu Apr 16

zxing-cpp provides Python bindings for the high-performance C++ port of the ZXing barcode library. It supports reading and writing a wide range of 1D and 2D barcode formats like QR Code, Data Matrix, UPC-A, and Code 128. The current version is 3.0.0, and it maintains an active development and release cadence, typically tied to its underlying C++ library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to both read and write barcodes using `zxing-cpp`. Reading typically involves loading an image with OpenCV (`cv2`) and passing it to `zxingcpp.read_barcodes`. Writing involves creating a barcode object with `zxingcpp.create_barcode`, converting it to an image array, and saving it using a library like Pillow (`PIL`).

import zxingcpp
import cv2
from PIL import Image
import numpy as np

# --- Example 1: Reading a barcode from an image (requires OpenCV) ---
# Create a dummy image with a QR code (in a real scenario, load from file)
# For demonstration, we'll generate one and save it
def generate_and_save_qr_code(text, filename="test_qr.png"):
    barcode_obj = zxingcpp.create_barcode(text, zxingcpp.BarcodeFormat.QRCode, ec_level="50%")
    img_array = barcode_obj.to_image(scale=5)
    Image.fromarray(img_array).save(filename)
    print(f"Generated '{filename}' for reading example.")

qr_text = "Hello, zxing-cpp!"
generate_and_save_qr_code(qr_text)

# Read the generated image
img = cv2.imread('test_qr.png')
if img is not None:
    results = zxingcpp.read_barcodes(img)
    if results:
        for result in results:
            print(f"\nFound barcode (read):\n  Text: '{result.text}'\n  Format: {result.format}\n  Position: {result.position}")
    else:
        print("\nCould not find any barcode in test_qr.png.")
else:
    print("\nError: Could not load test_qr.png for reading.")

# --- Example 2: Writing a barcode to an image (requires Pillow) ---
text_to_encode = "This is a test from zxing-cpp Python!"
barcode_format = zxingcpp.BarcodeFormat.DataMatrix

try:
    # Create a barcode object
    barcode = zxingcpp.create_barcode(
        text_to_encode, 
        barcode_format,
        ec_level="L" # For DataMatrix, 'L' is a common error correction level
    )

    # Convert the barcode to a NumPy array image
    img_array = barcode.to_image(scale=2) # Scale up for better visibility

    # Convert NumPy array to PIL Image and save
    pil_img = Image.fromarray(img_array)
    output_filename = "output_barcode.png"
    pil_img.save(output_filename)
    print(f"\nSuccessfully wrote {barcode_format} barcode to '{output_filename}'")

    # Optionally, convert to SVG string
    svg_string = barcode.to_svg(add_quiet_zones=True)
    svg_filename = "output_barcode.svg"
    with open(svg_filename, "w") as f:
        f.write(svg_string)
    print(f"Successfully wrote {barcode_format} barcode to '{svg_filename}'")

except Exception as e:
    print(f"\nError writing barcode: {e}")

view raw JSON →