{"id":7889,"library":"zxing-cpp","title":"zxing-cpp Python Bindings","description":"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.","status":"active","version":"3.0.0","language":"en","source_language":"en","source_url":"https://github.com/zxing-cpp/zxing-cpp.git","tags":["barcode","image processing","qr code","1d barcode","2d barcode","computer vision"],"install":[{"cmd":"pip install zxing-cpp","lang":"bash","label":"Stable release"},{"cmd":"pip install zxing-cpp --no-binary zxing-cpp","lang":"bash","label":"Build from source (requires C++20 compiler)"}],"dependencies":[{"reason":"Commonly used for image handling, especially when writing barcodes.","package":"Pillow","optional":true},{"reason":"Commonly used for image handling, especially when reading barcodes.","package":"opencv-python","optional":true},{"reason":"Required for building from source if pre-built wheels are not available.","package":"C++20 compiler","optional":false},{"reason":"Required for building the Python module from source.","package":"CMake >=3.18","optional":false}],"imports":[{"symbol":"zxingcpp","correct":"import zxingcpp"},{"symbol":"BarcodeFormat","correct":"from zxingcpp import BarcodeFormat"},{"symbol":"read_barcodes","correct":"import zxingcpp\n# ...\nbarcodes = zxingcpp.read_barcodes(image_data)"},{"symbol":"create_barcode","correct":"import zxingcpp\n# ...\nbarcode = zxingcpp.create_barcode(text, zxingcpp.BarcodeFormat.QRCode)"}],"quickstart":{"code":"import zxingcpp\nimport cv2\nfrom PIL import Image\nimport numpy as np\n\n# --- Example 1: Reading a barcode from an image (requires OpenCV) ---\n# Create a dummy image with a QR code (in a real scenario, load from file)\n# For demonstration, we'll generate one and save it\ndef generate_and_save_qr_code(text, filename=\"test_qr.png\"):\n    barcode_obj = zxingcpp.create_barcode(text, zxingcpp.BarcodeFormat.QRCode, ec_level=\"50%\")\n    img_array = barcode_obj.to_image(scale=5)\n    Image.fromarray(img_array).save(filename)\n    print(f\"Generated '{filename}' for reading example.\")\n\nqr_text = \"Hello, zxing-cpp!\"\ngenerate_and_save_qr_code(qr_text)\n\n# Read the generated image\nimg = cv2.imread('test_qr.png')\nif img is not None:\n    results = zxingcpp.read_barcodes(img)\n    if results:\n        for result in results:\n            print(f\"\\nFound barcode (read):\\n  Text: '{result.text}'\\n  Format: {result.format}\\n  Position: {result.position}\")\n    else:\n        print(\"\\nCould not find any barcode in test_qr.png.\")\nelse:\n    print(\"\\nError: Could not load test_qr.png for reading.\")\n\n# --- Example 2: Writing a barcode to an image (requires Pillow) ---\ntext_to_encode = \"This is a test from zxing-cpp Python!\"\nbarcode_format = zxingcpp.BarcodeFormat.DataMatrix\n\ntry:\n    # Create a barcode object\n    barcode = zxingcpp.create_barcode(\n        text_to_encode, \n        barcode_format,\n        ec_level=\"L\" # For DataMatrix, 'L' is a common error correction level\n    )\n\n    # Convert the barcode to a NumPy array image\n    img_array = barcode.to_image(scale=2) # Scale up for better visibility\n\n    # Convert NumPy array to PIL Image and save\n    pil_img = Image.fromarray(img_array)\n    output_filename = \"output_barcode.png\"\n    pil_img.save(output_filename)\n    print(f\"\\nSuccessfully wrote {barcode_format} barcode to '{output_filename}'\")\n\n    # Optionally, convert to SVG string\n    svg_string = barcode.to_svg(add_quiet_zones=True)\n    svg_filename = \"output_barcode.svg\"\n    with open(svg_filename, \"w\") as f:\n        f.write(svg_string)\n    print(f\"Successfully wrote {barcode_format} barcode to '{svg_filename}'\")\n\nexcept Exception as e:\n    print(f\"\\nError writing barcode: {e}\")\n","lang":"python","description":"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`)."},"warnings":[{"fix":"Update barcode creation and writing code to use the new `create_barcode` API and the updated `BarcodeFormat` and `BarcodeFormats` classes as shown in the quickstart example. Refer to the official README for details.","message":"Version 3.0.0 introduced significant changes to the creator/writer API, including `BarcodeFormat` and `BarcodeFormats` implementations. The old writer API (`write_barcode`) is now deprecated and `create_barcode` is the default.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure your development environment meets the C++20 compiler and CMake version requirements if you are building `zxing-cpp` from source or using the `--no-binary zxing-cpp` installation option.","message":"Building `zxing-cpp` from source now explicitly requires a C++20 compliant compiler (e.g., GCC 11+, Clang 12+, VS 2019 16.10+) and CMake 3.18 or newer for the Python module. Without pre-built wheels, this can cause build failures.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always verify file paths using `os.path.exists()` or convert to absolute paths with `os.path.abspath()`. Use raw strings (`r'C:\\path\\to\\file'`) or forward slashes (`'C:/path/to/file'`) for consistency on Windows.","message":"When reading images, especially from file paths, ensure the path is correct and accessible. `FileNotFoundError` is a common issue, particularly on Windows where path separators (`\\` vs `/`) or relative vs. absolute paths can cause problems.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If your application frequently processes images with many barcodes, consider pre-processing the image to isolate individual barcodes, or evaluate alternative libraries if multi-barcode detection is critical and `zxing-cpp`'s performance is insufficient for your specific use case.","message":"`zxing-cpp` is highly optimized for single barcode detection but may struggle with images containing multiple barcodes, exhibiting lower success rates compared to some other libraries in such scenarios.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Double-check the file path. Use an absolute path or ensure your relative path is correct from the script's current working directory (`os.getcwd()`). On Windows, ensure path separators are handled correctly (e.g., `r'C:\\path\\image.png'` or `'C:/path/image.png'`).","cause":"The image file specified in `cv2.imread()` or similar image loading function does not exist at the given path or is inaccessible.","error":"FileNotFoundError: [WinError 2] The system cannot find the file specified"},{"fix":"Improve image quality (ensure good lighting, focus, contrast). Try rotating or downscaling the image before passing it to `read_barcodes`. Ensure the barcode format is one of the supported types by `zxing-cpp`. For critical cases, inspect image binarization/thresholding parameters or consider `try_rotate` and `try_downscale` options in `read_barcodes` for more robust detection.","cause":"The `read_barcodes` function returned an empty list, indicating no barcode was detected. This can be due to poor image quality (blur, low resolution, bad lighting, shadows, angle), an unsupported barcode format, or the barcode being too small/damaged.","error":"Could not find any barcode."},{"fix":"Consult the `zxing-cpp` documentation or the `PYBIND11_MODULE` definition in the C++ source for the exact properties and their types on the `Barcode` object. For position, it's typically a string that needs parsing if numerical coordinates are required. Common attributes include `text`, `format`, `content_type`, `position`.","cause":"Attempting to access a non-existent attribute on the `Barcode` result object. This often happens if users expect a different data structure for properties like 'position' (e.g., direct x,y tuples instead of a string representation) or misremember attribute names.","error":"AttributeError: 'Barcode' object has no attribute 'some_attribute'"}]}