Completed
Push — master ( 36e2d9...033daa )
by Bjørn
03:15
created

Imagick::checkOperationality()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 8.7414

Importance

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