Debian Codegraph @

vendor/chillerlan/php-qrcode/src/Output/QRGdImage.php

raw
1 <?php
2 /**
3 * Class QRGdImage
4 *
5 * @created 05.12.2015
6 * @author Smiley <[email protected]>
7 * @copyright 2015 Smiley
8 * @license MIT
9 *
10 * @noinspection PhpComposerExtensionStubsInspection
11 */
12 declare(strict_types=1);
13
14 namespace chillerlan\QRCode\Output;
15
16 use chillerlan\QRCode\QROptions;
17 use chillerlan\QRCode\Data\QRMatrix;
18 use chillerlan\Settings\SettingsContainerInterface;
19 use GdImage;
20 use function extension_loaded, imagecolorallocate, imagecolortransparent, imagecreatetruecolor,
21 imagefilledellipse, imagefilledrectangle, imagescale, imagetypes, intdiv, intval, is_iterable,
22 max, min, ob_end_clean, ob_get_contents, ob_start, sprintf;
23 use const IMG_AVIF, IMG_BMP, IMG_GIF, IMG_JPG, IMG_PNG, IMG_WEBP;
24
25 /**
26 * Converts the matrix into GD images, raw or base64 output (requires ext-gd)
27 *
28 * @see https://php.net/manual/book.image.php
29 * @see https://github.com/chillerlan/php-qrcode/issues/223
30 */
31 abstract class QRGdImage extends QROutputAbstract{
32 use RGBArrayModuleValueTrait;
33
34 /**
35 * The GD image resource
36 *
37 * @see imagecreatetruecolor()
38 */
39 protected GdImage $image;
40
41 /**
42 * The allocated background color
43 *
44 * @see \imagecolorallocate()
45 */
46 protected int $background;
47
48 /**
49 * Whether we're running in upscale mode (scale < 20)
50 *
51 * @see \chillerlan\QRCode\QROptions::$drawCircularModules
52 */
53 protected bool $upscaled = false;
54
55 /**
56 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
57 * @noinspection PhpMissingParentConstructorInspection
58 */
59 public function __construct(SettingsContainerInterface|QROptions|iterable $options, QRMatrix $matrix){
60
61 if(is_iterable($options)){
62 $options = new QROptions($options);
63 }
64
65 $this->options = $options;
66 $this->matrix = $matrix;
67
68 $this->checkGD();
69
70 if($this->options->invertMatrix){
71 $this->matrix->invert();
72 }
73
74 $this->copyVars();
75 $this->setMatrixDimensions();
76 }
77
78 /**
79 * Checks whether GD is installed and if the given mode is supported
80 *
81 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
82 * @codeCoverageIgnore
83 */
84 protected function checkGD():void{
85
86 if(!extension_loaded('gd')){
87 throw new QRCodeOutputException('ext-gd not loaded');
88 }
89
90 $modes = [
91 QRGdImageAVIF::class => IMG_AVIF,
92 QRGdImageBMP::class => IMG_BMP,
93 QRGdImageGIF::class => IMG_GIF,
94 QRGdImageJPEG::class => IMG_JPG,
95 QRGdImagePNG::class => IMG_PNG,
96 QRGdImageWEBP::class => IMG_WEBP,
97 ];
98
99 // likely using custom output/manual invocation
100 if(!isset($modes[$this->options->outputInterface])){
101 return;
102 }
103
104 $mode = $modes[$this->options->outputInterface];
105
106 if((imagetypes() & $mode) !== $mode){
107 throw new QRCodeOutputException(sprintf('output mode "%s" not supported', $this->options->outputInterface));
108 }
109
110 }
111
112 /**
113 * @inheritDoc
114 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
115 */
116 protected function prepareModuleValue(mixed $value):int{
117 $values = [];
118
119 foreach(array_values($value) as $i => $val){
120
121 if($i > 2){
122 break;
123 }
124
125 $values[] = max(0, min(255, intval($val)));
126 }
127
128 /** @phan-suppress-next-line PhanParamTooFewInternalUnpack */
129 $color = imagecolorallocate($this->image, ...$values);
130
131 if($color === false){
132 throw new QRCodeOutputException('could not set color: imagecolorallocate() error');
133 }
134
135 return $color;
136 }
137
138 protected function getDefaultModuleValue(bool $isDark):int{
139 return $this->prepareModuleValue(($isDark) ? [0, 0, 0] : [255, 255, 255]);
140 }
141
142 /**
143 * @inheritDoc
144 *
145 * @throws \ErrorException|\chillerlan\QRCode\Output\QRCodeOutputException
146 */
147 public function dump(string|null $file = null):string|GdImage{
148 $this->image = $this->createImage();
149 // set module values after image creation because we need the GdImage instance
150 $this->setModuleValues();
151 $this->setBgColor();
152
153 if(imagefilledrectangle($this->image, 0, 0, $this->length, $this->length, $this->background) === false){
154 throw new QRCodeOutputException('imagefilledrectangle() error');
155 }
156
157 $this->drawImage();
158
159 if($this->upscaled){
160 // scale down to the expected size
161 $scaled = imagescale($this->image, ($this->length / 10), ($this->length / 10));
162
163 if($scaled === false){
164 throw new QRCodeOutputException('imagescale() error');
165 }
166
167 $this->image = $scaled;
168 $this->upscaled = false;
169 // Reset scaled and length values after rescaling image to prevent issues with subclasses that use the output from dump()
170 $this->setMatrixDimensions();
171 }
172
173 // set transparency after scaling, otherwise it would be undone
174 // @see https://www.php.net/manual/en/function.imagecolortransparent.php#77099
175 $this->setTransparencyColor();
176
177 if($this->options->returnResource){
178 return $this->image;
179 }
180
181 $imageData = $this->dumpImage();
182
183 $this->saveToFile($imageData, $file);
184
185 if($this->options->outputBase64){
186 $imageData = $this->toBase64DataURI($imageData);
187 }
188
189 return $imageData;
190 }
191
192 /**
193 * Creates a new GdImage resource and scales it if necessary
194 *
195 * we're scaling the image up in order to draw crisp round circles, otherwise they appear square-y on small scales
196 *
197 * @see https://github.com/chillerlan/php-qrcode/issues/23
198 *
199 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
200 */
201 protected function createImage():GdImage{
202
203 if($this->drawCircularModules && $this->options->gdImageUseUpscale && $this->options->scale < 20){
204 // increase the initial image size by 10
205 $this->length *= 10;
206 $this->scale *= 10;
207 $this->upscaled = true;
208 }
209
210 $im = imagecreatetruecolor($this->length, $this->length);
211
212 if($im === false){
213 throw new QRCodeOutputException('imagecreatetruecolor() error');
214 }
215
216 return $im;
217 }
218
219 /**
220 * Sets the background color
221 */
222 protected function setBgColor():void{
223
224 if(isset($this->background)){
225 return;
226 }
227
228 if($this::moduleValueIsValid($this->options->bgColor)){
229 $this->background = $this->prepareModuleValue($this->options->bgColor);
230
231 return;
232 }
233
234 $this->background = $this->prepareModuleValue([255, 255, 255]);
235 }
236
237 /**
238 * Sets the transparency color, returns the identifier of the new transparent color
239 */
240 protected function setTransparencyColor():int{
241
242 if(!$this->options->imageTransparent){
243 return -1;
244 }
245
246 $transparencyColor = $this->background;
247
248 if($this::moduleValueIsValid($this->options->transparencyColor)){
249 $transparencyColor = $this->prepareModuleValue($this->options->transparencyColor);
250 }
251
252 return imagecolortransparent($this->image, $transparencyColor);
253 }
254
255 /**
256 * Returns the image quality value for the current GdImage output child class (defaults to -1 ... 100)
257 */
258 protected function getQuality():int{
259 return max(-1, min(100, $this->options->quality));
260 }
261
262 /**
263 * Draws the QR image
264 */
265 protected function drawImage():void{
266 foreach($this->matrix->getMatrix() as $y => $row){
267 foreach($row as $x => $M_TYPE){
268 $this->module($x, $y, $M_TYPE);
269 }
270 }
271 }
272
273 /**
274 * Creates a single QR pixel with the given settings
275 */
276 protected function module(int $x, int $y, int $M_TYPE):void{
277
278 if(!$this->drawLightModules && !$this->matrix->isDark($M_TYPE)){
279 return;
280 }
281
282 $color = $this->getModuleValue($M_TYPE);
283
284 if($this->drawCircularModules && !$this->matrix->checkTypeIn($x, $y, $this->keepAsSquare)){
285 imagefilledellipse(
286 $this->image,
287 (($x * $this->scale) + intdiv($this->scale, 2)),
288 (($y * $this->scale) + intdiv($this->scale, 2)),
289 (int)($this->circleDiameter * $this->scale),
290 (int)($this->circleDiameter * $this->scale),
291 $color,
292 );
293
294 return;
295 }
296
297 imagefilledrectangle(
298 $this->image,
299 ($x * $this->scale),
300 ($y * $this->scale),
301 (($x + 1) * $this->scale),
302 (($y + 1) * $this->scale),
303 $color,
304 );
305 }
306
307 /**
308 * Renders the image with the gdimage function for the desired output
309 *
310 * @see https://github.com/chillerlan/php-qrcode/issues/223
311 */
312 abstract protected function renderImage():void;
313
314 /**
315 * Creates the final image by calling the desired GD output function
316 *
317 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
318 */
319 protected function dumpImage():string{
320 ob_start();
321
322 $this->renderImage();
323
324 $imageData = ob_get_contents();
325
326 if($imageData === false){
327 throw new QRCodeOutputException('ob_get_contents() error');
328 }
329
330 ob_end_clean();
331
332 return $imageData;
333 }
334
335 }