Debian Codegraph @

src/Renderer/GDLibRenderer.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace BaconQrCode\Renderer;
6
7 use BaconQrCode\Encoder\ByteMatrix;
8 use BaconQrCode\Encoder\MatrixUtil;
9 use BaconQrCode\Encoder\QrCode;
10 use BaconQrCode\Exception\InvalidArgumentException;
11 use BaconQrCode\Exception\RuntimeException;
12 use BaconQrCode\Renderer\Color\Alpha;
13 use BaconQrCode\Renderer\Color\ColorInterface;
14 use BaconQrCode\Renderer\RendererStyle\EyeFill;
15 use BaconQrCode\Renderer\RendererStyle\Fill;
16 use GdImage;
17
18 final class GDLibRenderer implements RendererInterface
19 {
20 private ?GdImage $image;
21
22 /**
23 * @var array<string, int>
24 */
25 private array $colors;
26
27 public function __construct(
28 private int $size,
29 private int $margin = 4,
30 private string $imageFormat = 'png',
31 private int $compressionQuality = 9,
32 private ?Fill $fill = null
33 ) {
34 if (! extension_loaded('gd') || ! function_exists('gd_info')) {
35 throw new RuntimeException('You need to install the GD extension to use this back end');
36 }
37
38 if ($this->fill === null) {
39 $this->fill = Fill::default();
40 }
41 if ($this->fill->hasGradientFill()) {
42 throw new InvalidArgumentException('GDLibRenderer does not support gradients');
43 }
44 }
45
46 /**
47 * @throws InvalidArgumentException if matrix width doesn't match height
48 */
49 public function render(QrCode $qrCode): string
50 {
51 $matrix = $qrCode->getMatrix();
52 $matrixSize = $matrix->getWidth();
53
54 if ($matrixSize !== $matrix->getHeight()) {
55 throw new InvalidArgumentException('Matrix must have the same width and height');
56 }
57
58 MatrixUtil::removePositionDetectionPatterns($matrix);
59 $this->newImage();
60 $this->draw($matrix);
61
62 return $this->renderImage();
63 }
64
65 private function newImage(): void
66 {
67 $img = imagecreatetruecolor($this->size, $this->size);
68 if ($img === false) {
69 throw new RuntimeException('Failed to create image of that size');
70 }
71
72 $this->image = $img;
73 imagealphablending($this->image, false);
74 imagesavealpha($this->image, true);
75
76
77 $bg = $this->getColor($this->fill->getBackgroundColor());
78 imagefilledrectangle($this->image, 0, 0, $this->size, $this->size, $bg);
79 imagealphablending($this->image, true);
80 }
81
82 private function draw(ByteMatrix $matrix): void
83 {
84 $matrixSize = $matrix->getWidth();
85
86 $pointsOnSide = $matrix->getWidth() + $this->margin * 2;
87 $pointInPx = $this->size / $pointsOnSide;
88
89 $this->drawEye(0, 0, $pointInPx, $this->fill->getTopLeftEyeFill());
90 $this->drawEye($matrixSize - 7, 0, $pointInPx, $this->fill->getTopRightEyeFill());
91 $this->drawEye(0, $matrixSize - 7, $pointInPx, $this->fill->getBottomLeftEyeFill());
92
93 $rows = $matrix->getArray()->toArray();
94 $color = $this->getColor($this->fill->getForegroundColor());
95 for ($y = 0; $y < $matrixSize; $y += 1) {
96 for ($x = 0; $x < $matrixSize; $x += 1) {
97 if (! $rows[$y][$x]) {
98 continue;
99 }
100
101 $points = $this->normalizePoints([
102 ($this->margin + $x) * $pointInPx, ($this->margin + $y) * $pointInPx,
103 ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y) * $pointInPx,
104 ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y + 1) * $pointInPx,
105 ($this->margin + $x) * $pointInPx, ($this->margin + $y + 1) * $pointInPx,
106 ]);
107 imagefilledpolygon($this->image, $points, $color);
108 }
109 }
110 }
111
112 private function drawEye(int $xOffset, int $yOffset, float $pointInPx, EyeFill $eyeFill): void
113 {
114 $internalColor = $this->getColor($eyeFill->inheritsInternalColor()
115 ? $this->fill->getForegroundColor()
116 : $eyeFill->getInternalColor());
117
118 $externalColor = $this->getColor($eyeFill->inheritsExternalColor()
119 ? $this->fill->getForegroundColor()
120 : $eyeFill->getExternalColor());
121
122 for ($y = 0; $y < 7; $y += 1) {
123 for ($x = 0; $x < 7; $x += 1) {
124 if ((($y === 1 || $y === 5) && $x > 0 && $x < 6) || (($x === 1 || $x === 5) && $y > 0 && $y < 6)) {
125 continue;
126 }
127
128 $points = $this->normalizePoints([
129 ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx,
130 ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx,
131 ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx,
132 ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx,
133 ]);
134
135 if ($y > 1 && $y < 5 && $x > 1 && $x < 5) {
136 imagefilledpolygon($this->image, $points, $internalColor);
137 } else {
138 imagefilledpolygon($this->image, $points, $externalColor);
139 }
140 }
141 }
142 }
143
144 /**
145 * Normalize points will trim right and bottom line by 1 pixel.
146 * Otherwise pixels of neighbors are overlapping which leads to issue with transparency and small QR codes.
147 */
148 private function normalizePoints(array $points): array
149 {
150 $maxX = $maxY = 0;
151 for ($i = 0; $i < count($points); $i += 2) {
152 // Do manual round as GD just removes decimal part
153 $points[$i] = $newX = round($points[$i]);
154 $points[$i + 1] = $newY = round($points[$i + 1]);
155
156 $maxX = max($maxX, $newX);
157 $maxY = max($maxY, $newY);
158 }
159
160 // Do trimming only if there are 4 points (8 coordinates), assumes this is square.
161
162 for ($i = 0; $i < count($points); $i += 2) {
163 $points[$i] = min($points[$i], $maxX - 1);
164 $points[$i + 1] = min($points[$i + 1], $maxY - 1);
165 }
166
167 return $points;
168 }
169
170 private function renderImage(): string
171 {
172 ob_start();
173 $quality = $this->compressionQuality;
174 switch ($this->imageFormat) {
175 case 'png':
176 if ($quality > 9 || $quality < 0) {
177 $quality = 9;
178 }
179 imagepng($this->image, null, $quality);
180 break;
181
182 case 'gif':
183 imagegif($this->image, null);
184 break;
185
186 case 'jpeg':
187 case 'jpg':
188 if ($quality > 100 || $quality < 0) {
189 $quality = 85;
190 }
191 imagejpeg($this->image, null, $quality);
192 break;
193 default:
194 ob_end_clean();
195 throw new InvalidArgumentException(
196 'Supported image formats are jpeg, png and gif, got: ' . $this->imageFormat
197 );
198 }
199
200 $this->colors = [];
201 $this->image = null;
202
203 return ob_get_clean();
204 }
205
206 private function getColor(ColorInterface $color): int
207 {
208 $alpha = 100;
209
210 if ($color instanceof Alpha) {
211 $alpha = $color->getAlpha();
212 $color = $color->getBaseColor();
213 }
214
215 $rgb = $color->toRgb();
216
217 $colorKey = sprintf('%02X%02X%02X%02X', $rgb->getRed(), $rgb->getGreen(), $rgb->getBlue(), $alpha);
218
219 if (! isset($this->colors[$colorKey])) {
220 $colorId = imagecolorallocatealpha(
221 $this->image,
222 $rgb->getRed(),
223 $rgb->getGreen(),
224 $rgb->getBlue(),
225 (int)((100 - $alpha) / 100 * 127) // Alpha for GD is in range 0 (opaque) - 127 (transparent)
226 );
227
228 if ($colorId === false) {
229 throw new RuntimeException('Failed to create color: #' . $colorKey);
230 }
231
232 $this->colors[$colorKey] = $colorId;
233 }
234
235 return $this->colors[$colorKey];
236 }
237 }