Current Location: Home> Latest Articles> How to Generate a QR Code with a Background Image Using PHP?

How to Generate a QR Code with a Background Image Using PHP?

gitbox 2025-06-18

Introduction

QR codes are matrix barcodes that can store large amounts of information in a small space. In today's world, QR codes have become a convenient way to scan and transmit information. In web development, QR codes are often used to convey information. In this article, we'll explore how to generate a QR code with a background image using PHP, and how to customize the QR code to suit your needs.

Step 1: Install and Enable the QR Code Generation Package

The first step to generating QR codes in PHP is to install and enable the QR Code generation package. This package requires PHP version 5.3 or higher and the php-gd library. You can install the QR Code generation package using the following terminal command:

composer require endroid/qr-code

Step 2: Create the QR Code Object

When creating the QR Code object, you need to set some basic properties such as the size and the content of the QR code. In this example, we will create a 300x300 pixel QR code and add a background image. The QR Code generator package provides a variety of options for customization, which you can adjust according to your needs.


use Endroid\QrCode\QrCode;
use Endroid\QrCode\ErrorCorrectionLevel;

$qrCode = new QrCode('Hello World!');
$qrCode->setSize(300);
$qrCode->setMargin(10);
$qrCode->setErrorCorrectionLevel(new ErrorCorrectionLevel(ErrorCorrectionLevel::HIGH));
$qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]);
        

In the code above, we create a new QR Code object and set the following properties:

  • Data: 'Hello World!'
  • Size: 300x300
  • Margin: 10
  • Error correction: High
  • Foreground color: Transparent

Step 3: Add the Background Image

To add a background image to the QR code, we need to use PHP's GD library. By using this library, we can overlay the QR Code image on top of the background image, creating a custom QR code with a personalized look.


$bg = imagecreatefromjpeg('background.jpg');
$qrCodeImage = $qrCode->get('png');
$image = imagecreatefromstring($qrCodeImage);

list($qrWidth, $qrHeight) = getimagesizefromstring($qrCodeImage);

imagecopyresampled(
    $bg,
    $image,
    50, 50, 0, 0,
    $qrWidth, $qrHeight, 
    $qrWidth, $qrHeight
);

header('Content-Type: image/png');
imagepng($bg);
        

In the code above, we first load the background image, then create a QR Code image. Next, we retrieve the dimensions of the QR Code image and overlay it onto the background image. Finally, we output the combined image in PNG format using PHP's imagepng function. You can customize the size, position, and rotation of the QR Code as needed.

At this point, we have successfully generated a QR code with a background image. By using PHP to generate QR codes, you can easily customize the design of your QR codes to meet various requirements.