endroid/qr-code

repository·main·Indexed 26 days ago

https://github.com/endroid/qr-code

A PHP library for generating QR codes with support for formats including PNG, WebP, SVG, and EPS. Built on top of bacon/bacon-qr-code, it features a fluent Builder for configuration, support for logos and labels, and validation of generated codes. It provides options for round block size modes and integrates with Symfony via the endroid/qr-code-bundle.

Tokens
2.1K
Snippets
5
Records
9
Agent score
39%

What's inside endroid/qr-code

  1. Handle QR code results

    main

    Once a QR code is generated, the $result object allows you to output it in several ways:

    • Direct Output: Send the raw string to the browser with the correct MIME type.
    • Save to File: Write the image directly to the filesystem.
    • Data URI: Generate a base64 encoded string for inline use in <img> tags.
    // Directly output the QR code
    header('Content-Type: '.$result->getMimeType());
    echo $result->getString();
    
    // Save it to a file
    $result->saveToFile(__DIR__.'/qrcode.png');
    
    // Generate a data URI to include image data inline (i.e. inside an <img> tag)
    $dataUri = $result->getDataUri();
  2. Install the QR Code library

    main

    Install the library using Composer. If you intend to generate image files (like PNG or WebP), ensure the PHP GD extension is enabled and configured on your system.

    composer require endroid/qr-code
  3. Integrate with Symfony

    main

    The endroid/qr-code-bundle provides deep integration for Symfony applications, allowing you to:

    • Configure global defaults (size, writer, etc.).
    • Use multiple configurations via injection aliases.
    • Generate QR codes via URLs (e.g., /qr-code/<config>/Hello).
    • Use dedicated functions in Twig templates.
  4. Validate generated QR codes

    main
    To ensure a generated QR code is readable and contains the exact expected data, you can enable validation. This is disabled by default because it affects performance. You can enable it via the Builder (validateResult: true) or by calling $writer->validateResult($result, 'expected data') on a writer that supports it.
  5. Generate a QR code using the Builder

    main

    The Builder provides a fluent way to configure and generate a QR code in a single step. You can specify the writer, data, encoding, error correction level, size, margin, logo, and labels.

    use Endroid
    QrCode
    Builder
    Builder;
    use Endroid
    QrCode
    Encoding
    Encoding;
    use Endroid
    QrCode
    ErrorCorrectionLevel;
    use Endroid
    QrCode
    Label
    LabelAlignment;
    use Endroid
    QrCode
    Label
    Font
    OpenSans;
    use Endroid
    QrCode
    RoundBlockSizeMode;
    use Endroid
    QrCode
    Writer
    PngWriter;
    
    $builder = new Builder(
        writer: new PngWriter(),
        writerOptions: [],
        validateResult: false,
        data: 'Custom QR code contents',
        encoding: new Encoding('UTF-8'),
        errorCorrectionLevel: ErrorCorrectionLevel::High,
        size: 300,
        margin: 10,
        roundBlockSizeMode: RoundBlockSizeMode::Margin,
        logoPath: __DIR__.'/assets/bender.png',
        logoResizeToWidth: 50,
        logoPunchoutBackground: true,
        labelText: 'This is the label',
        labelFont: new OpenSans(20),
        labelAlignment: LabelAlignment::Center
    );
    
    $result = $builder->build();
  6. Generate a QR code without the Builder

    main

    For more granular control, you can manually instantiate QrCode, Logo, and Label objects, then pass them to a Writer instance.

    use Endroid
    QrCode
    Color
    Color;
    use Endroid
    QrCode
    Encoding
    Encoding;
    use Endroid
    QrCode
    ErrorCorrectionLevel;
    use Endroid
    QrCode
    QrCode;
    use Endroid
    QrCode
    Label
    Label;
    use Endroid
    QrCode
    Logo
    Logo;
    use Endroid
    QrCode
    RoundBlockSizeMode;
    use Endroid
    QrCode
    Writer
    PngWriter;
    use Endroid
    QrCode
    Writer
    ValidationException;
    
    $writer = new PngWriter();
    
    // Create QR code
    $qrCode = new QrCode(
        data: 'Life is too short to be generating QR codes',
        encoding: new Encoding('UTF-8'),
        errorCorrectionLevel: ErrorCorrectionLevel::Low,
        size: 300,
        margin: 10,
        roundBlockSizeMode: RoundBlockSizeMode::Margin,
        foregroundColor: new Color(0, 0, 0),
        backgroundColor: new Color(255, 255, 255)
    );
    
    // Create generic logo
    $logo = new Logo(
        path: __DIR__.'/assets/bender.png',
        resizeToWidth: 50,
        punchoutBackground: true
    );
    
    // Create generic label
    $label = new Label(
        text: 'Label',
        textColor: new Color(255, 0, 0)
    );
    
    $result = $writer->write($qrCode, $logo, $label);
    
    // Validate the result
    $writer->validateResult($result, 'Life is too short to be generating QR codes');
  7. Configure Round Block Size Mode

    main

    Rounding block sizes ensures sharp images and better readability. You can choose between several modes using RoundBlockSizeMode:

    • margin (default): Shrinks the QR code if necessary to keep the final image size constant, adding extra margin instead.
    • enlarge: Enlarges both the QR code and the final image when rounding occurs.
    • shrink: Shrinks both the QR code and the final image when rounding occurs.
    • none: No rounding. Recommended for vector formats like SVG.
  8. Configure Writer options

    main

    Different writers support specific configuration options via constants prefixed with WRITER_OPTION_. You can pass these into the Builder via the writerOptions array.

    Available Options

    WriterOptionDescription
    PdfWriterunitunit of measurement (default: mm)
    fpdfPDF to place the image in (default: new PDF)
    ximage offset (default: 0)
    yimage offset (default: 0)
    linka URL or an identifier returned by AddLink()
    PngWritercompression_levelcompression level (0-9, default: -1 = zlib default)
    number_of_colorsnumber of colors (1-256, null for true color and transparency)
    SvgWriterblock_idid of the block element for external reference (default: block)
    exclude_xml_declarationexclude XML declaration (default: false)
    exclude_svg_width_and_heightexclude width and height (default: false)
    force_xlink_hrefforces xlink namespace (default: false)
    compactuse path element vs defs/use (default: true)
    WebPWriterqualityimage quality (0-100, default: 80)
    use Endroid
    QrCode
    Builder
    Builder;
    use Endroid
    QrCode
    Writer
    SvgWriter;
    
    $builder = new Builder(
        writer: new SvgWriter(),
        writerOptions: [
            SvgWriter::WRITER_OPTION_EXCLUDE_XML_DECLARATION => true
        ]
    );