Passed
Push — master ( 1ada49...6f88dc )
by Bjørn
02:29
created

Imagick   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 151
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 151
rs 10
c 0
b 0
f 0
wmc 16

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checkConvertability() 0 19 5
A checkOperationality() 0 16 4
A getOptionDefinitionsExtra() 0 3 1
B doActualConvert() 0 89 6
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
    protected function doActualConvert()
75
    {
76
        $options = $this->options;
77
78
        try {
79
            $im = new \Imagick($this->source);
80
        } catch (\Exception $e) {
81
            throw new ConversionFailedException(
82
                'Failed creating Gmagick object of file',
83
                'Failed creating Gmagick object of file: "' . $this->source . '" - Imagick threw an exception.',
84
                $e
85
            );
86
        }
87
88
        //$im = new \Imagick();
89
        //$im->readImage($this->source);
90
91
        $im->setImageFormat('WEBP');
92
93
        /*
94
         * More about iMagick's WebP options:
95
         * http://www.imagemagick.org/script/webp.php
96
         * https://developers.google.com/speed/webp/docs/cwebp
97
         * https://stackoverflow.com/questions/37711492/imagemagick-specific-webp-calls-in-php
98
         */
99
100
        // TODO: We could easily support all webp options with a loop
101
102
        /*
103
        After using getImageBlob() to write image, the following setOption() calls
104
        makes settings makes imagick fail. So can't use those. But its a small price
105
        to get a converter that actually makes great quality conversions.
106
107
        $im->setOption('webp:method', strval($options['method']));
108
        $im->setOption('webp:low-memory', strval($options['low-memory']));
109
        $im->setOption('webp:lossless', strval($options['lossless']));
110
        */
111
112
        if ($options['metadata'] == 'none') {
113
            // Strip metadata and profiles
114
            $im->stripImage();
115
        }
116
117
        if ($this->isQualityDetectionRequiredButFailing()) {
118
            // Luckily imagick is a big boy, and automatically converts with same quality as
119
            // source, when the quality isn't set.
120
            // So we simply do not set quality.
121
            // This actually kills the max-quality functionality. But I deem that this is more important
122
            // because setting image quality to something higher than source generates bigger files,
123
            // but gets you no extra quality. When failing to limit quality, you at least get something
124
            // out of it
125
            $this->logLn('Converting without setting quality, to achieve auto quality');
126
        } else {
127
            $im->setImageCompressionQuality($this->getCalculatedQuality());
128
        }
129
130
        // https://stackoverflow.com/questions/29171248/php-imagick-jpeg-optimization
131
        // setImageFormat
132
133
        // TODO: Read up on
134
        // https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
135
        // https://github.com/nwtn/php-respimg
136
137
        // TODO:
138
        // Should we set alpha channel for PNG's like suggested here:
139
        // https://gauntface.com/blog/2014/09/02/webp-support-with-imagemagick-and-php ??
140
        // It seems that alpha channel works without... (at least I see completely transparerent pixels)
141
142
        // TODO: Check out other iMagick methods, see http://php.net/manual/de/imagick.writeimage.php#114714
143
        // 1. file_put_contents($destination, $im)
144
        // 2. $im->writeImage($destination)
145
146
        // We used to use writeImageFile() method. But we now use getImageBlob(). See issue #43
147
        //$success = $im->writeImageFile(fopen($destination, 'wb'));
148
149
        try {
150
            $imageBlob = $im->getImageBlob();
151
        } catch (\ImagickException $e) {
152
            throw new ConversionFailedException(
153
                'Imagick failed converting - getImageBlob() threw an exception)',
154
                0,
155
                $e
156
            );
157
        }
158
159
        $success = file_put_contents($this->destination, $imageBlob);
160
161
        if (!$success) {
162
            throw new CreateDestinationFileException('Failed writing file');
163
        }
164
165
        // Btw: check out processWebp() method here:
166
        // https://github.com/Intervention/image/blob/master/src/Intervention/Image/Imagick/Encoder.php
167
    }
168
}
169