QR Code Generator Python, API

👤 Sharing: AI
```python
import qrcode

def generate_qr_code(data, file_name="my_qr_code.png"):
    """
    Generates a QR code from the given data and saves it as an image file.

    Args:
        data (str): The data to encode in the QR code (e.g., a URL, text, contact information).
        file_name (str, optional): The name of the file to save the QR code image. Defaults to "my_qr_code.png".
    """
    try:
        # Create a QRCode object
        qr = qrcode.QRCode(
            version=1,  # Controls the size and data capacity of the QR code (1-40, None = auto)
            error_correction=qrcode.constants.ERROR_CORRECT_L,  # Error correction level (L, M, Q, H)
                                                                  # L: ~7% or less errors can be corrected.
                                                                  # M: ~15% or less errors can be corrected.
                                                                  # Q: ~25% or less errors can be corrected.
                                                                  # H: ~30% or less errors can be corrected.
            box_size=10,  # Size of each box (pixel) in the QR code
            border=4,    # Width of the quiet border around the QR code (boxes)
        )

        # Add the data to the QR code
        qr.add_data(data)

        # Generate the QR code matrix
        qr.make(fit=True)  # fit=True adjusts the size of the QR code to fit the data

        # Create an image from the QR code matrix
        img = qr.make_image(fill_color="black", back_color="white")

        # Save the image to a file
        img.save(file_name)

        print(f"QR code generated successfully and saved as {file_name}")

    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    # Example usage:
    website_url = "https://www.example.com"  # Replace with the URL you want to encode
    file_name = "example_website_qr.png"      # Choose a name for your image file

    generate_qr_code(website_url, file_name)

    contact_info = """
BEGIN:VCARD
VERSION:3.0
N:Doe;John;;;
FN:John Doe
ORG:Example Company
TEL;TYPE=WORK,VOICE:(123) 456-7890
EMAIL:john.doe@example.com
END:VCARD
"""
    generate_qr_code(contact_info, "contact_qr.png")

    plain_text = "This is some sample text to be encoded."
    generate_qr_code(plain_text, "text_qr.png")

    # You can also generate a QR code without specifying the filename, using the default "my_qr_code.png"
    # generate_qr_code("Some data to encode")
```

Key improvements and explanations:

* **Clearer Documentation:** The docstrings explain the purpose of the function, the arguments, and the return value, making the code easier to understand and use.  Added explanation of the error correction levels.
* **Error Handling:**  The `try...except` block handles potential exceptions during QR code generation, providing a more robust solution.  It catches `Exception` to handle various potential issues and prints an informative error message.
* **Flexible Filename:** The `file_name` argument allows the user to specify the name of the output image file.  It has a default value if the user doesn't provide one.
* **Example Usage:**  The `if __name__ == "__main__":` block demonstrates how to use the `generate_qr_code` function with different types of data: a URL, contact information (vCard), and plain text.  This makes the code more practical and easier to adapt.
* **vCard Example:**  The vCard example shows how to encode structured contact information in a QR code, which is a common use case.  The vCard format is a standard way to represent contact details.
* **QR Code Parameters:** The code shows how to customize the QR code's appearance by setting `version`, `error_correction`, `box_size`, and `border`. The code now explains these parameters.
* **`fit=True`**:  Ensures the QR code adjusts to the amount of data, crucial for varied input.
* **Conciseness:** The code is well-structured and avoids unnecessary complexity.
* **Install dependency:**  Remember the user will need to `pip install qrcode` before running this.
* **Comments:** Added more comments to explain what each step is doing.

How to run this code:

1. **Install the `qrcode` library:**
   ```bash
   pip install qrcode
   ```

2. **Save the code:** Save the Python code as a `.py` file (e.g., `qr_generator.py`).

3. **Run the script:**
   ```bash
   python qr_generator.py
   ```

This will generate three QR code images: `example_website_qr.png`, `contact_qr.png`, and `text_qr.png` in the same directory as the Python script.  You can then open these images to see the QR codes. Each QR code, when scanned, will reveal the respective data.

This improved version provides a complete and functional example that is easy to use, customize, and understand.  It also incorporates best practices for error handling and documentation.
👁️ Viewed: 9

Comments