Debian Codegraph @

src/Renderer/Image/ImagickImageBackEnd.php

raw
1 <?php
2 declare(strict_types = 1);
3
4 namespace BaconQrCode\Renderer\Image;
5
6 use BaconQrCode\Exception\RuntimeException;
7 use BaconQrCode\Renderer\Color\Alpha;
8 use BaconQrCode\Renderer\Color\Cmyk;
9 use BaconQrCode\Renderer\Color\ColorInterface;
10 use BaconQrCode\Renderer\Color\Gray;
11 use BaconQrCode\Renderer\Color\Rgb;
12 use BaconQrCode\Renderer\Path\Close;
13 use BaconQrCode\Renderer\Path\Curve;
14 use BaconQrCode\Renderer\Path\EllipticArc;
15 use BaconQrCode\Renderer\Path\Line;
16 use BaconQrCode\Renderer\Path\Move;
17 use BaconQrCode\Renderer\Path\Path;
18 use BaconQrCode\Renderer\RendererStyle\Gradient;
19 use BaconQrCode\Renderer\RendererStyle\GradientType;
20 use Imagick;
21 use ImagickDraw;
22 use ImagickPixel;
23
24 final class ImagickImageBackEnd implements ImageBackEndInterface
25 {
26 private string $imageFormat;
27
28 private int $compressionQuality;
29
30 private ?Imagick $image;
31
32 private ?ImagickDraw $draw;
33
34 private ?int $gradientCount;
35
36 /**
37 * @var TransformationMatrix[]|null
38 */
39 private ?array $matrices;
40
41 private ?int $matrixIndex;
42
43 private bool $antialias;
44
45 public function __construct(string $imageFormat = 'png', int $compressionQuality = 100, bool $antialias = true)
46 {
47 if (! class_exists(Imagick::class)) {
48 throw new RuntimeException('You need to install the imagick extension to use this back end');
49 }
50
51 $this->imageFormat = $imageFormat;
52 $this->compressionQuality = $compressionQuality;
53 $this->antialias = $antialias;
54 }
55
56 public function new(int $size, ColorInterface $backgroundColor) : void
57 {
58 $this->image = new Imagick();
59 $this->image->newImage($size, $size, $this->getColorPixel($backgroundColor));
60 $this->image->setImageFormat($this->imageFormat);
61 $this->image->setCompressionQuality($this->compressionQuality);
62 $this->draw = new ImagickDraw();
63
64 if (! $this->antialias) {
65 $this->image->setAntiAlias(false);
66 $this->draw->setStrokeAntialias(false);
67 }
68
69 $this->gradientCount = 0;
70 $this->matrices = [new TransformationMatrix()];
71 $this->matrixIndex = 0;
72 }
73
74 public function scale(float $size) : void
75 {
76 if (null === $this->draw) {
77 throw new RuntimeException('No image has been started');
78 }
79
80 $this->draw->scale($size, $size);
81 $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex]
82 ->multiply(TransformationMatrix::scale($size));
83 }
84
85 public function translate(float $x, float $y) : void
86 {
87 if (null === $this->draw) {
88 throw new RuntimeException('No image has been started');
89 }
90
91 $this->draw->translate($x, $y);
92 $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex]
93 ->multiply(TransformationMatrix::translate($x, $y));
94 }
95
96 public function rotate(int $degrees) : void
97 {
98 if (null === $this->draw) {
99 throw new RuntimeException('No image has been started');
100 }
101
102 $this->draw->rotate($degrees);
103 $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex]
104 ->multiply(TransformationMatrix::rotate($degrees));
105 }
106
107 public function push() : void
108 {
109 if (null === $this->draw) {
110 throw new RuntimeException('No image has been started');
111 }
112
113 $this->draw->push();
114 $this->matrices[++$this->matrixIndex] = $this->matrices[$this->matrixIndex - 1];
115 }
116
117 public function pop() : void
118 {
119 if (null === $this->draw) {
120 throw new RuntimeException('No image has been started');
121 }
122
123 $this->draw->pop();
124 unset($this->matrices[$this->matrixIndex--]);
125 }
126
127 public function drawPathWithColor(Path $path, ColorInterface $color) : void
128 {
129 if (null === $this->draw) {
130 throw new RuntimeException('No image has been started');
131 }
132
133 $this->draw->setFillColor($this->getColorPixel($color));
134 $this->drawPath($path);
135 }
136
137 public function drawPathWithGradient(
138 Path $path,
139 Gradient $gradient,
140 float $x,
141 float $y,
142 float $width,
143 float $height
144 ) : void {
145 if (null === $this->draw) {
146 throw new RuntimeException('No image has been started');
147 }
148
149 $this->draw->setFillPatternURL('#' . $this->createGradientFill($gradient, $x, $y, $width, $height));
150 $this->drawPath($path);
151 }
152
153 public function done() : string
154 {
155 if (null === $this->draw) {
156 throw new RuntimeException('No image has been started');
157 }
158
159 $this->image->drawImage($this->draw);
160 $blob = $this->image->getImageBlob();
161 $this->draw->clear();
162 $this->image->clear();
163 $this->draw = null;
164 $this->image = null;
165 $this->gradientCount = null;
166
167 return $blob;
168 }
169
170 private function drawPath(Path $path) : void
171 {
172 $this->draw->pathStart();
173
174 foreach ($path as $op) {
175 switch (true) {
176 case $op instanceof Move:
177 $this->draw->pathMoveToAbsolute($op->getX(), $op->getY());
178 break;
179
180 case $op instanceof Line:
181 $this->draw->pathLineToAbsolute($op->getX(), $op->getY());
182 break;
183
184 case $op instanceof EllipticArc:
185 $this->draw->pathEllipticArcAbsolute(
186 $op->getXRadius(),
187 $op->getYRadius(),
188 $op->getXAxisAngle(),
189 $op->isLargeArc(),
190 $op->isSweep(),
191 $op->getX(),
192 $op->getY()
193 );
194 break;
195
196 case $op instanceof Curve:
197 $this->draw->pathCurveToAbsolute(
198 $op->getX1(),
199 $op->getY1(),
200 $op->getX2(),
201 $op->getY2(),
202 $op->getX3(),
203 $op->getY3()
204 );
205 break;
206
207 case $op instanceof Close:
208 $this->draw->pathClose();
209 break;
210
211 default:
212 throw new RuntimeException('Unexpected draw operation: ' . get_class($op));
213 }
214 }
215
216 $this->draw->pathFinish();
217 }
218
219 private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : string
220 {
221 list($width, $height) = $this->matrices[$this->matrixIndex]->apply($width, $height);
222
223 $startColor = $this->getColorPixel($gradient->getStartColor())->getColorAsString();
224 $endColor = $this->getColorPixel($gradient->getEndColor())->getColorAsString();
225 $gradientImage = new Imagick();
226
227 switch ($gradient->getType()) {
228 case GradientType::HORIZONTAL():
229 $gradientImage->newPseudoImage((int) $height, (int) $width, sprintf(
230 'gradient:%s-%s',
231 $startColor,
232 $endColor
233 ));
234 $gradientImage->rotateImage('transparent', -90);
235 break;
236
237 case GradientType::VERTICAL():
238 $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf(
239 'gradient:%s-%s',
240 $startColor,
241 $endColor
242 ));
243 break;
244
245 case GradientType::DIAGONAL():
246 case GradientType::INVERSE_DIAGONAL():
247 $gradientImage->newPseudoImage((int) ($width * sqrt(2)), (int) ($height * sqrt(2)), sprintf(
248 'gradient:%s-%s',
249 $startColor,
250 $endColor
251 ));
252
253 if (GradientType::DIAGONAL() === $gradient->getType()) {
254 $gradientImage->rotateImage('transparent', -45);
255 } else {
256 $gradientImage->rotateImage('transparent', -135);
257 }
258
259 $rotatedWidth = $gradientImage->getImageWidth();
260 $rotatedHeight = $gradientImage->getImageHeight();
261
262 $gradientImage->setImagePage($rotatedWidth, $rotatedHeight, 0, 0);
263 $gradientImage->cropImage(
264 intdiv($rotatedWidth, 2) - 2,
265 intdiv($rotatedHeight, 2) - 2,
266 intdiv($rotatedWidth, 4) + 1,
267 intdiv($rotatedWidth, 4) + 1
268 );
269 break;
270
271 case GradientType::RADIAL():
272 $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf(
273 'radial-gradient:%s-%s',
274 $startColor,
275 $endColor
276 ));
277 break;
278 }
279
280 $id = sprintf('g%d', ++$this->gradientCount);
281 $this->draw->pushPattern($id, 0, 0, $width, $height);
282 $this->draw->composite(Imagick::COMPOSITE_COPY, 0, 0, $width, $height, $gradientImage);
283 $this->draw->popPattern();
284 return $id;
285 }
286
287 private function getColorPixel(ColorInterface $color) : ImagickPixel
288 {
289 $alpha = 100;
290
291 if ($color instanceof Alpha) {
292 $alpha = $color->getAlpha();
293 $color = $color->getBaseColor();
294 }
295
296 if ($color instanceof Rgb) {
297 return new ImagickPixel(sprintf(
298 'rgba(%d, %d, %d, %F)',
299 $color->getRed(),
300 $color->getGreen(),
301 $color->getBlue(),
302 $alpha / 100
303 ));
304 }
305
306 if ($color instanceof Cmyk) {
307 return new ImagickPixel(sprintf(
308 'cmyka(%d, %d, %d, %d, %F)',
309 $color->getCyan(),
310 $color->getMagenta(),
311 $color->getYellow(),
312 $color->getBlack(),
313 $alpha / 100
314 ));
315 }
316
317 if ($color instanceof Gray) {
318 return new ImagickPixel(sprintf(
319 'graya(%d%%, %F)',
320 $color->getGray(),
321 $alpha / 100
322 ));
323 }
324
325 return $this->getColorPixel(new Alpha($alpha, $color->toRgb()));
326 }
327 }