Skip to content

Novis\Image\QrCode::render

Novis\Image\QrCode::render(
    string $data,
    ?{ size?: uint, margin?: uint, level?: Level, format?: Format } $options = null,
): bytes

Makes a QR code: a square image that a phone camera can read back to text.

QrCode::render takes a string, such as a link, and returns the QR code as an image file. By default the file is a PNG of 256 by 256 pixels, with a white border of 4 squares on every side.

The options change the image. size is the width and height in pixels. margin is the width of the border, in squares. level is a QrCode::Level, and sets how much damage a scanner can repair. format is the file Format.

Text too long for the level throws a LogicError. A size smaller than the code, or too big for the pixel limit, also throws a LogicError.

Good to know: a longer text or a higher level makes a code with more squares, so it needs a bigger size.

The examples below show a link with the default options, setting the size, border and format, and the two errors.

Parameters

  • $datastring
  • $options?{ size?: uint, margin?: uint, level?: Level, format?: Format }default null

Return value

Returns bytes.

Examples

A link as a qr code

<?nvs
// Shows how to make a QR code for a link with the default options.
use Novis\Image\Image;
use Novis\Image\QrCode;
bytes $code = QrCode::render('https://example.com/orders/1042');
// The result is a PNG file of 256 by 256 pixels.
var $info = Image::info($code);
echo $info->width, ' by ', $info->height, " pixels\n";
echo Image::mime($info->format), "\n";
Output
256 by 256 pixels
image/png

Size margin and format

<?nvs
// Shows how to set the size, the white border and the file format of a QR code.
use Novis\Image\Format;
use Novis\Image\Image;
use Novis\Image\QrCode;
// `margin` is the width of the white border, counted in squares of the code.
// `level: QrCode::Level::High` lets a scanner read the code even when part of it is covered.
bytes $code = QrCode::render('Shop order 1042', {
size: 120,
margin: 2,
level: QrCode::Level::High,
format: Format::Jpeg,
});
// This prints 120 by 120 pixels and the JPEG MIME type.
var $info = Image::info($code);
echo $info->width, ' by ', $info->height, " pixels\n";
echo Image::mime($info->format), "\n";
Output
120 by 120 pixels
image/jpeg

Text too long

<?nvs
// Shows the error `render` throws when the text does not fit in a QR code.
use Novis\Image\QrCode;
// A QR code holds at most a few thousand characters.
// This text has 5000, so `render` throws a `LogicError`.
string $text = Core\Str::repeat('a', 5000);
try {
QrCode::render($text);
echo "made a code\n";
} catch (LogicError $e) {
echo "too long: LogicError\n";
}
// A `size` smaller than the code also throws a `LogicError`.
try {
QrCode::render('https://example.com', { size: 10 });
echo "made a code\n";
} catch (LogicError $e) {
echo "too small: LogicError\n";
}
Output
too long: LogicError
too small: LogicError