1<?php
2
3namespace Mpdf\QrCode\Output;
4
5use Mpdf\QrCode\QrCode;
6
7class Png
8{
9
10	/**
11	 * @param \Mpdf\QrCode\QrCode $qrCode QR code instance
12	 * @param int $w QR code width in pixels
13	 * @param int[] $background RGB background color
14	 * @param int[] $color RGB foreground and border color
15	 * @param int $compression Level (0 - no compression, 9 - greatest compression)
16	 *
17	 * @return string Binary image data
18	 */
19	public function output(QrCode $qrCode, $w = 100, $background = [255, 255, 255], $color = [0, 0, 0], $compression = 0)
20	{
21		$qrSize = $qrCode->getQrSize();
22		$final = $qrCode->getFinal();
23
24		if ($qrCode->isBorderDisabled()) {
25			$minSize = 4;
26			$maxSize = $qrSize - 4;
27		} else {
28			$minSize = 0;
29			$maxSize = $qrSize;
30		}
31
32		$size = $w;
33		$s = $size / ($maxSize - $minSize);
34
35		$im = imagecreatetruecolor($size, $size);
36		$foregroundColor = imagecolorallocate($im, $color[0], $color[1], $color[2]);
37		$backgroundColor = imagecolorallocate($im, $background[0], $background[1], $background[2]);
38		imagefilledrectangle($im, 0, 0, $size, $size, $backgroundColor);
39
40		for ($j = $minSize; $j < $maxSize; $j++) {
41			for ($i = $minSize; $i < $maxSize; $i++) {
42				if ($final[$i + $j * $qrSize + 1]) {
43					imagefilledrectangle(
44						$im,
45						(int) round(($i - $minSize) * $s),
46						(int) round(($j - $minSize) * $s),
47						(int) round(($i - $minSize + 1) * $s - 1),
48						(int) round(($j - $minSize + 1) * $s - 1),
49						$foregroundColor
50					);
51				}
52			}
53		}
54
55		ob_start();
56		imagepng($im, null, $compression);
57		$data = ob_get_contents();
58		ob_end_clean();
59
60		imagedestroy($im);
61
62		return $data;
63	}
64
65}
66