Passed
Push — master ( 74ce7c...3af96c )
by Bjørn
03:41
created

Imagick::supportsLossless()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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