Passed
Push — master ( 943cd5...e87575 )
by Bjørn
02:27
created

Imagick::checkOperationality()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 0
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace WebPConvert\Convert\Converters;
4
5
use WebPConvert\Convert\BaseConverters\AbstractConverter;
6
use WebPConvert\Convert\Exceptions\ConversionFailedException;
7
use WebPConvert\Convert\Exceptions\ConversionFailed\FileSystemProblems\CreateDestinationFileException;
8
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperational\SystemRequirementsNotMetException;
9
10
//use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\TargetNotFoundException;
11
12
class Imagick extends AbstractConverter
13
{
14
    protected function getOptionDefinitionsExtra()
15
    {
16
        return [];
17
    }
18
19
    /**
20
     * Check operationality of Imagick converter.
21
     *
22
     * Note:
23
     * It may be that Gd has been compiled without jpeg support or png support.
24
     * We do not check for this here, as the converter could still be used for the other.
25
     *
26
     * @throws SystemRequirementsNotMetException  if system requirements are not met
27
     */
28
    protected function checkOperationality()
29
    {
30
        if (!extension_loaded('imagick')) {
31
            throw new SystemRequirementsNotMetException('Required iMagick extension is not available.');
32
        }
33
34
        if (!class_exists('\\Imagick')) {
35
            throw new SystemRequirementsNotMetException(
36
                'iMagick is installed, but not correctly. The class Imagick is not available'
37
            );
38
        }
39
40
        $im = new \Imagick();
41
42
        if (!in_array('WEBP', $im->queryFormats())) {
43
            throw new SystemRequirementsNotMetException('iMagick was compiled without WebP support.');
44
        }
45
    }
46
47
    /**
48
     * Check if specific file is convertable with current converter / converter settings.
49
     *
50
     * @throws SystemRequirementsNotMetException  if Imagick does not support image type
51
     */
52
    protected function checkConvertability()
53
    {
54
        $im = new \Imagick();
55
        $mimeType = $this->getMimeTypeOfSource();
56
        switch ($mimeType) {
57
            case 'image/png':
58
                if (!in_array('PNG', $im->queryFormats())) {
59
                    throw new SystemRequirementsNotMetException(
60
                        'Imagick has been compiled without PNG support and can therefore not convert this PNG image.'
61
                    );
62
                }
63
                break;
64
            case 'image/jpeg':
65
                if (!in_array('JPEG', $im->queryFormats())) {
66
                    throw new SystemRequirementsNotMetException(
67
                        'Imagick has been compiled without Jpeg support and can therefore not convert this Jpeg image.'
68
                    );
69
                }
70
                break;
71
        }
72
    }
73
74
    /**
75
     *
76
     * @throws ImagickException if imagick throws an exception
77
     * @throws CreateDestinationFileException if imageblob could not be saved to file
78
     */
79
    protected function doActualConvert()
80
    {
81
        $options = $this->options;
82
83
        // This might throw - we let it!
84
        $im = new \Imagick($this->source);
85
86
        //$im = new \Imagick();
87
        //$im->readImage($this->source);
88
89
        $im->setImageFormat('WEBP');
90
91
        /*
92
         * More about iMagick's WebP options:
93
         * http://www.imagemagick.org/script/webp.php
94
         * https://developers.google.com/speed/webp/docs/cwebp
95
         * https://stackoverflow.com/questions/37711492/imagemagick-specific-webp-calls-in-php
96
         */
97
98
        // TODO: We could easily support all webp options with a loop
99
100
        /*
101
        After using getImageBlob() to write image, the following setOption() calls
102
        makes settings makes imagick fail. So can't use those. But its a small price
103
        to get a converter that actually makes great quality conversions.
104
105
        $im->setOption('webp:method', strval($options['method']));
106
        $im->setOption('webp:low-memory', strval($options['low-memory']));
107
        $im->setOption('webp:lossless', strval($options['lossless']));
108
        */
109
110
        if ($options['metadata'] == 'none') {
111
            // Strip metadata and profiles
112
            $im->stripImage();
113
        }
114
115
        if ($this->isQualityDetectionRequiredButFailing()) {
116
            // Luckily imagick is a big boy, and automatically converts with same quality as
117
            // source, when the quality isn't set.
118
            // So we simply do not set quality.
119
            // This actually kills the max-quality functionality. But I deem that this is more important
120
            // because setting image quality to something higher than source generates bigger files,
121
            // but gets you no extra quality. When failing to limit quality, you at least get something
122
            // out of it
123
            $this->logLn('Converting without setting quality in order to achieve auto quality');
124
        } else {
125
            $im->setImageCompressionQuality($this->getCalculatedQuality());
126
        }
127
128
        // https://stackoverflow.com/questions/29171248/php-imagick-jpeg-optimization
129
        // setImageFormat
130
131
        // TODO: Read up on
132
        // https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
133
        // https://github.com/nwtn/php-respimg
134
135
        // TODO:
136
        // Should we set alpha channel for PNG's like suggested here:
137
        // https://gauntface.com/blog/2014/09/02/webp-support-with-imagemagick-and-php ??
138
        // It seems that alpha channel works without... (at least I see completely transparerent pixels)
139
140
        // TODO: Check out other iMagick methods, see http://php.net/manual/de/imagick.writeimage.php#114714
141
        // 1. file_put_contents($destination, $im)
142
        // 2. $im->writeImage($destination)
143
144
        // We used to use writeImageFile() method. But we now use getImageBlob(). See issue #43
145
        //$success = $im->writeImageFile(fopen($destination, 'wb'));
146
147
148
        // This might throw - we let it!
149
        $imageBlob = $im->getImageBlob();
150
151
        $success = file_put_contents($this->destination, $imageBlob);
152
153
        if (!$success) {
154
            throw new CreateDestinationFileException('Failed writing file');
155
        }
156
157
        // Btw: check out processWebp() method here:
158
        // https://github.com/Intervention/image/blob/master/src/Intervention/Image/Imagick/Encoder.php
159
    }
160
}
161