Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.95% covered (warning)
82.95%
107 / 129
86.21% covered (warning)
86.21%
25 / 29
CRAP
0.00% covered (danger)
0.00%
0 / 1
Convert
82.95% covered (warning)
82.95%
107 / 129
86.21% covered (warning)
86.21%
25 / 29
56.50
0.00% covered (danger)
0.00%
0 / 1
 input
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 output
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 in
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
4.02
 out
71.43% covered (warning)
71.43%
10 / 14
0.00% covered (danger)
0.00%
0 / 1
5.58
 getCommand
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 execute
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 raw
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 gravity
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 density
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 profile
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 removeProfile
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 changeProfile
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 rotate
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 background
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 resample
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 size
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 flatten
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 strip
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 flip
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 flop
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 type
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 layers
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 resize
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 crop
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 quality
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 colorspace
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 sepia
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 polaroid
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 bordercolor
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * Karla ImageMagick wrapper library
5 *
6 * PHP Version 8.0<
7 *
8 * @category Utility
9 * @author   Johannes Skov Frandsen <jsf@greenoak.dk>
10 * @license  http://www.opensource.org/licenses/mit-license.php MIT
11 * @link     https://github.com/localgod/karla Karla
12 * @since    2012-04-05
13 */
14
15declare(strict_types=1);
16
17namespace Karla\Program;
18
19use InvalidArgumentException;
20use RuntimeException;
21use Karla\Action\Resize;
22use Karla\Action\Gravity;
23use Karla\Action\Density;
24use Karla\Action\Profile;
25use Karla\Action\Rotate;
26use Karla\Action\Background;
27use Karla\Action\Resample;
28use Karla\Action\Size;
29use Karla\Action\Flatten;
30use Karla\Action\Strip;
31use Karla\Action\Flip;
32use Karla\Action\Flop;
33use Karla\Action\Type;
34use Karla\Action\Layers;
35use Karla\Action\Crop;
36use Karla\Action\Quality;
37use Karla\Action\Colorspace;
38use Karla\Action\Sepia;
39use Karla\Action\Polaroid;
40use Karla\Action\Bordercolor;
41use Karla\Program;
42use Karla\Cache;
43use Karla\CommandBuilder;
44use Karla\Query;
45use Karla\PathValidator;
46
47/**
48 * Class for wrapping ImageMagicks convert tool
49 *
50 * @category Utility
51 * @author   Johannes Skov Frandsen <jsf@greenoak.dk>
52 * @license  http://www.opensource.org/licenses/mit-license.php MIT
53 * @link     https://github.com/localgod/karla Karla
54 */
55class Convert extends ImageMagick implements Program
56{
57    /**
58     * Input file
59     *
60     * @var string
61     */
62    protected string $inputFile = '';
63
64    /**
65     * Output file
66     *
67     * @var string
68     */
69    protected string $outputFile = '';
70
71    /**
72     * Add input file
73     *
74     * @param string $filePath Input file path
75     *
76     * @throws \InvalidArgumentException
77     */
78    public function input(string $filePath): self
79    {
80        return $this->in($filePath);
81    }
82
83    /**
84     * Add output file
85     *
86     * @param string $filePath Output file path
87     * @param bool $includeOptions Include the used options as part of the filename
88     *
89     * @throws \InvalidArgumentException
90     */
91    public function output(string $filePath, bool $includeOptions = false): self
92    {
93        return $this->out($filePath, $includeOptions);
94    }
95
96    /**
97     * Add input argument
98     *
99     * @param string $filePath Input file path
100     *
101     * @throws \InvalidArgumentException
102     * @deprecated Since 1.2.0, use input() instead. Will be removed in 2.0.0.
103     */
104    public function in(string $filePath): self
105    {
106        if (str_contains($filePath, "\0")) {
107            throw new InvalidArgumentException('Path contains null bytes');
108        }
109        if (! file_exists($filePath)) {
110            $message = 'The input file path (' . $filePath . ') is invalid or the file could not be located.';
111            throw new InvalidArgumentException($message);
112        }
113
114        $filePath = PathValidator::validatePath($filePath);
115
116        if (is_writeable($filePath)) {
117            $this->inputFile = escapeshellarg($filePath);
118        }
119
120        return $this;
121    }
122
123    /**
124     * Add output argument
125     *
126     * @param string $filePath Output file path
127     * @param bool $includeOptions Include the used options as part of the filename
128     *
129     * @throws \InvalidArgumentException
130     * @todo Implement include options to filename
131     * @deprecated Since 1.2.0, use output() instead. Will be removed in 2.0.0.
132     */
133    public function out(string $filePath, bool $includeOptions = false): self
134    {
135        $pathinfo = pathinfo($filePath);
136        $dirname = $pathinfo['dirname'] ?? '.';
137        if (str_contains($dirname, "\0")) {
138            throw new InvalidArgumentException('Path contains null bytes');
139        }
140        if (! file_exists($dirname)) {
141            $message = 'The output file path (' . $dirname . ') is invalid or could not be located.';
142            throw new InvalidArgumentException($message);
143        }
144        if (! is_writeable($dirname)) {
145            $message = 'The output file path (' . $dirname . ') is not writable.';
146            throw new InvalidArgumentException($message);
147        }
148        if (! $includeOptions) {
149            $this->outputFile = escapeshellarg($dirname . '/' . $pathinfo['basename']);
150        } else {
151            // TODO implement this feature
152            $this->outputFile = escapeshellarg($dirname . '/' . $pathinfo['basename']);
153        }
154
155        return $this;
156    }
157
158    /**
159     * Get the command to run
160     *
161     * @see ImageMagick::getCommand()
162     */
163    public function getCommand(): string
164    {
165        if ($this->outputFile == '') {
166            throw new RuntimeException('Can not perform convert without an output file');
167        }
168        if ($this->inputFile == '') {
169            throw new RuntimeException('Can not perform convert without an input file');
170        }
171
172        return (new CommandBuilder($this->getQuery(), $this->binPath, $this->bin, $this->version))
173            ->setInput($this->inputFile)
174            ->setOutput($this->outputFile)
175            ->build();
176    }
177
178    /**
179     * Execute the command
180     *
181     * @param bool $reset Reset after execution
182     *
183     * @see ImageMagick::execute()
184     */
185    public function execute(bool $reset = true): string
186    {
187        if ($this->cache instanceof Cache) {
188            if (! $this->cache->isCached($this->inputFile, $this->outputFile, $this->getQuery()->getInputOptions())) {
189                parent::execute(false);
190                $this->cache->setCache($this->inputFile, $this->outputFile, $this->getQuery()->getInputOptions());
191                shell_exec('rm ' . $this->outputFile);
192                $out = $this->cache->getCached(
193                    $this->inputFile,
194                    $this->outputFile,
195                    $this->getQuery()->getInputOptions()
196                );
197                $this->getQuery()->reset();
198                return $out;
199            }
200            return $this->cache->getCached($this->inputFile, $this->outputFile, $this->getQuery()->getInputOptions());
201        } else {
202            parent::execute();
203            shell_exec('chmod 666 ' . $this->outputFile);
204            return $this->outputFile;
205        }
206    }
207
208    /**
209     * Raw arguments directly to ImageMagick
210     *
211     * @param string $arguments Arguments
212     * @param bool $input Defaults to an input option, use false to use it as an output option
213     *
214     * @see ImageMagick::raw()
215     */
216    public function raw(string $arguments, bool $input = true): self
217    {
218        parent::raw($arguments, $input);
219
220        return $this;
221    }
222
223    /**
224     * Set the gravity
225     *
226     * @param string $gravity Gravity
227     */
228    public function gravity(string $gravity): self
229    {
230        $action = new Gravity($this, $gravity);
231        $this->setQuery($action->perform($this->getQuery()));
232        return $this;
233    }
234
235    /**
236     * Set the density of the output image.
237     *
238     * @param int $width The width of the image
239     * @param int $height The height of the image
240     * @param bool $output If output is true density is set for the resulting image
241     *                     If output is false density is used for reading the input image
242     */
243    public function density(int $width = 72, int $height = 72, bool $output = true): self
244    {
245        $action = new Density($width, $height, $output);
246        $this->setQuery($action->perform($this->getQuery()));
247        return $this;
248    }
249
250    /**
251     * Add a profile to the image.
252     *
253     * @param string $profilePath Profile path
254     * @param string $profileName Profile name
255     */
256    public function profile(string $profilePath = "", string $profileName = ""): self
257    {
258        $action = new Profile($profilePath, $profileName);
259        $this->setQuery($action->perform($this->getQuery()));
260        return $this;
261    }
262
263    /**
264     * Remove a profile from the image.
265     *
266     * @param string $profileName Profile name
267     *
268     * @todo get list of profiles from image (can be done by identify but might be too expensive)
269     */
270    public function removeProfile(string $profileName): self
271    {
272        $action = new Profile('', $profileName, true);
273        $this->setQuery($action->perform($this->getQuery()));
274        return $this;
275    }
276
277    /**
278     * Change profile on the image.
279     *
280     * @param string $profilePathFrom Path to the profile
281     * @param string $profilePathTo Path to the profile
282     *
283     * @throws \InvalidArgumentException
284     */
285    public function changeProfile(string $profilePathFrom, string $profilePathTo): self
286    {
287        $this->getQuery()->notWith('profile', Query::ARGUMENT_TYPE_OUTPUT);
288        try {
289            $this->profile($profilePathFrom);
290        } catch (InvalidArgumentException $e) {
291            $message = $e->getMessage() . ' for input profile';
292            throw new InvalidArgumentException($message);
293        }
294        try {
295            $this->profile($profilePathTo);
296        } catch (InvalidArgumentException $e) {
297            $message = $e->getMessage() . ' for output profile';
298            throw new InvalidArgumentException($message);
299        }
300
301        return $this;
302    }
303
304    /**
305     * Rotate image
306     *
307     * @param int $degree Degrees to rotate the image
308     * @param string $background The background color to apply to empty triangles in the corners,
309     *                           left over from rotating the image
310     */
311    public function rotate(int $degree, string $background = '#ffffff'): self
312    {
313        $action = new Rotate($degree);
314        $this->setQuery($action->perform($this->getQuery()));
315        $this->background($background);
316        return $this;
317    }
318
319    /**
320     * Add a background color to a image
321     *
322     * @param string $color Color
323     */
324    public function background(string $color): self
325    {
326        $action = new Background($color);
327        $this->setQuery($action->perform($this->getQuery()));
328        return $this;
329    }
330
331    /**
332     * Resample the image to a new resolution
333     *
334     * @param int $newWidth New image resolution
335     * @param int|null $newHeight New image resolution
336     * @param int|null $originalWidth Original image resolution
337     * @param int|null $originalHeight Original image resolution
338     */
339    public function resample(
340        int $newWidth,
341        int|null $newHeight = null,
342        int|null $originalWidth = null,
343        int|null $originalHeight = null
344    ): self {
345        if ($originalWidth != null && $originalHeight != null) {
346            $this->density($originalWidth, $originalHeight, false);
347        }
348        if ($originalWidth != null && $originalHeight == null) {
349            $this->density($originalWidth, $originalWidth, false);
350        }
351
352        $action = new Resample($newWidth, $newHeight);
353        $this->setQuery($action->perform($this->getQuery()));
354        return $this;
355    }
356
357    /**
358     * Size the input image
359     *
360     * @param int|null $width Image width
361     * @param int|null $height Image height
362     */
363    public function size(int|null $width, int|null $height): self
364    {
365        $action = new Size($width, $height);
366        $this->setQuery($action->perform($this->getQuery()));
367        return $this;
368    }
369
370    /**
371     * Flatten layers in an image.
372     */
373    public function flatten(): self
374    {
375        $action = new Flatten();
376        $this->setQuery($action->perform($this->getQuery()));
377        return $this;
378    }
379
380    /**
381     * Strip image of any profiles or comments.
382     */
383    public function strip(): self
384    {
385        $action = new Strip();
386        $this->setQuery($action->perform($this->getQuery()));
387        return $this;
388    }
389
390    /**
391     * Flip image
392     */
393    public function flip(): self
394    {
395        $action = new Flip();
396        $this->setQuery($action->perform($this->getQuery()));
397        return $this;
398    }
399
400    /**
401     * Flop image
402     */
403    public function flop(): self
404    {
405        $action = new Flop();
406        $this->setQuery($action->perform($this->getQuery()));
407        return $this;
408    }
409
410    /**
411     * Set output image type
412     *
413     * @param string $type The output image type
414     */
415    public function type(string $type): self
416    {
417        $action = new Type($this, $type);
418        $this->setQuery($action->perform($this->getQuery()));
419        return $this;
420    }
421
422    /**
423     * Apply a method to layers in images.
424     *
425     * @param string $method The method to use
426     */
427    public function layers(string $method): self
428    {
429        $action = new Layers($this, $method);
430        $this->setQuery($action->perform($this->getQuery()));
431        return $this;
432    }
433
434    /**
435     * Resize the input image
436     *
437     * @param int|null $width Image width
438     * @param int|null $height Image height
439     * @param bool $maintainAspectRatio Should we maintain aspect ratio? default is true
440     * @param bool $dontScaleUp Should we prohibit scaling up? default is true
441     * @param string $aspect How should we handle aspect ratio?
442     */
443    public function resize(
444        int| null $width,
445        int| null $height,
446        bool $maintainAspectRatio = true,
447        bool $dontScaleUp = true,
448        string $aspect = Resize::ASPECT_FIT
449    ): self {
450        $action = new Resize($width, $height, $maintainAspectRatio, $dontScaleUp, $aspect);
451        $this->setQuery($action->perform($this->getQuery()));
452        return $this;
453    }
454
455    /**
456     * Resize the input image
457     *
458     * @param int $width Image width
459     * @param int $height Image height
460     * @param int $xOffset X offset from upper-left corner
461     * @param int $yOffset Y offset from upper-left corner
462     */
463    public function crop(int $width, int $height, int $xOffset = 0, int $yOffset = 0): self
464    {
465        $action = new Crop($width, $height, $xOffset, $yOffset);
466        $this->setQuery($action->perform($this->getQuery()));
467        return $this;
468    }
469
470    /**
471     * Set the quality of the output image for jpeg an png.
472     *
473     * @param int $quality A value between 0 - 100
474     * @param string $format Format to use; default is jpeg
475     */
476    public function quality(int $quality, string $format = 'jpeg'): self
477    {
478        $action = new Quality($quality, $format);
479        $this->setQuery($action->perform($this->getQuery()));
480        return $this;
481    }
482
483    /**
484     * Set the colorspace for the image
485     *
486     * @param string $colorSpace The colorspace to use
487     */
488    public function colorspace(string $colorSpace): self
489    {
490        $action = new Colorspace($this, $colorSpace);
491        $this->setQuery($action->perform($this->getQuery()));
492        return $this;
493    }
494
495    /**
496     * Sepia tone the image
497     *
498     * @param int $threshold The threshold to use
499     */
500    public function sepia(int $threshold = 80): self
501    {
502        $action = new Sepia($threshold);
503        $this->setQuery($action->perform($this->getQuery()));
504        return $this;
505    }
506
507    /**
508     * Add polaroid effect to the image
509     *
510     * @param int $angle The threshold to use
511     */
512    public function polaroid(int $angle = 0): self
513    {
514        $action = new Polaroid($angle);
515        $this->setQuery($action->perform($this->getQuery()));
516        return $this;
517    }
518
519    /**
520     * Set the color of the border if border is set
521     *
522     * @param string $color The color of the border
523     */
524    public function bordercolor(string $color = '#DFDFDF'): self
525    {
526        $action = new Bordercolor($color);
527        $this->setQuery($action->perform($this->getQuery()));
528        return $this;
529    }
530}