Test Failed
Pull Request — master (#2001)
by Arnaud
05:20
created

Image::convert()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 6
nop 3
dl 0
loc 13
ccs 4
cts 4
cp 1
crap 3
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Assets;
15
16
use Cecil\Exception\RuntimeException;
17
use Intervention\Image\ImageManagerStatic as ImageManager;
18
19
class Image
20
{
21
    /**
22
     * Resize an image Asset.
23
     *
24
     * @throws RuntimeException
25
     */
26
    public static function resize(Asset $asset, int $width, int $quality): string
27 1
    {
28
        try {
29 1
            // is image Asset?
30
            if ($asset['type'] !== 'image') {
31
                throw new RuntimeException(sprintf('Not an image.'));
32
            }
33 1
            // is GD is installed
34 1
            if (!\extension_loaded('gd')) {
35 1
                throw new RuntimeException('GD extension is required.');
36 1
            }
37 1
            // creates image object from source
38
            $image = ImageManager::make($asset['content_source']);
39 1
            // resizes to $width with constraint the aspect-ratio and unwanted upsizing
40 1
            $image->resize($width, null, function (\Intervention\Image\Constraint $constraint) {
41 1
                $constraint->aspectRatio();
42
                $constraint->upsize();
43
            });
44 1
            // interlaces (PNG) or progressives (JPEG) image
45 1
            $image->interlace();
46
            // save image in extension format and given quality
47
            $imageAsString = (string) $image->encode($asset['ext'], $quality);
48 1
            // destroy image object
49
            $image->destroy();
50
51
            return $imageAsString;
52
        } catch (\Exception $e) {
53
            throw new RuntimeException(sprintf('Not able to resize "%s": %s', $asset['path'], $e->getMessage()));
54 1
        }
55
    }
56 1
57 1
    /**
58 1
     * Converts an image Asset to the target format.
59 1
     *
60 1
     * @throws RuntimeException
61
     */
62
    public static function convert(Asset $asset, string $format, int $quality): string
63 1
    {
64 1
        try {
65
            if ($asset['type'] !== 'image') {
66
                throw new RuntimeException(sprintf('Not an image.'));
67 1
            }
68
            $image = ImageManager::make($asset['content']);
69
            $imageAsString = (string) $image->encode($format, $quality);
70
            $image->destroy();
71
72
            return $imageAsString;
73 1
        } catch (\Exception $e) {
74
            throw new RuntimeException(sprintf('Not able to resize "%s": %s', $asset['path'], $e->getMessage()));
75
        }
76
    }
77
78
    /**
79 1
     * Returns the Data URL (encoded in Base64).
80
     *
81 1
     * @throws RuntimeException
82
     */
83
    public static function getDataUrl(Asset $asset, int $quality): string
84
    {
85
        try {
86
            if ($asset['type'] != 'image' || self::isSVG($asset)) {
87
                throw new RuntimeException(sprintf('Not an image.'));
88
            }
89 1
            $image = ImageManager::make($asset['content']);
90
            $imageAsDataUrl = (string) $image->encode('data-url', $quality);
91 1
            $image->destroy();
92
93
            return $imageAsDataUrl;
94
        } catch (\Exception $e) {
95 1
            throw new RuntimeException(sprintf('Can\'t get Data URL of "%s": %s', $asset['path'], $e->getMessage()));
96 1
        }
97 1
    }
98 1
99 1
    /**
100
     * Returns the dominant hexadecimal color of an image asset.
101 1
     *
102
     * @throws RuntimeException
103
     */
104
    public static function getDominantColor(Asset $asset): string
105
    {
106
        try {
107
            if ($asset['type'] != 'image' || self::isSVG($asset)) {
108
                throw new RuntimeException(sprintf('Not an image.'));
109 1
            }
110
111 1
            $assetColor = clone $asset;
112
            $assetColor = $assetColor->resize(100);
113
            $image = ImageManager::make($assetColor['content']);
114
            $color = $image->limitColors(1)->pickColor(0, 0, 'hex');
115 1
            $image->destroy();
116 1
117
            return $color;
118 1
        } catch (\Exception $e) {
119
            throw new RuntimeException(sprintf('Can\'t get dominant color of "%s": %s', $asset['path'], $e->getMessage()));
120
        }
121
    }
122
123
    /**
124
     * Returns a Low Quality Image Placeholder (LQIP) as data URL.
125
     *
126
     * @throws RuntimeException
127
     */
128
    public static function getLqip(Asset $asset): string
129
    {
130
        try {
131
            if ($asset['type'] !== 'image') {
132
                throw new RuntimeException(sprintf('Not an image.'));
133
            }
134
            $assetLqip = clone $asset;
135
            $assetLqip = $assetLqip->resize(100);
136
            $image = ImageManager::make($assetLqip['content']);
137
            $imageAsString = (string) $image->blur(50)->encode('data-url');
138
            $image->destroy();
139
140
            return $imageAsString;
141
        } catch (\Exception $e) {
142
            throw new RuntimeException(sprintf('can\'t create LQIP of "%s": %s', $asset['path'], $e->getMessage()));
143
        }
144
    }
145
146
    /**
147
     * Build the `srcset` attribute for responsive images.
148
     * e.g.: `srcset="/img-480.jpg 480w, /img-800.jpg 800w"`.
149
     *
150
     * @throws RuntimeException
151
     */
152
    public static function buildSrcset(Asset $asset, array $widths): string
153
    {
154
        if ($asset['type'] !== 'image') {
155
            throw new RuntimeException(sprintf('can\'t build "srcset" of "%s": it\'s not an image file.', $asset['path']));
156
        }
157
158
        $srcset = '';
159
        $widthMax = 0;
160
        foreach ($widths as $width) {
161
            if ($asset['width'] < $width) {
162
                break;
163
            }
164
            $img = $asset->resize($width);
165
            $srcset .= sprintf('%s %sw, ', (string) $img, $width);
166
            $widthMax = $width;
167
        }
168
        // adds source image
169
        if (!empty($srcset) && ($asset['width'] < max($widths) && $asset['width'] != $widthMax)) {
170
            $srcset .= sprintf('%s %sw', (string) $asset, $asset['width']);
171
        }
172
173
        return rtrim($srcset, ', ');
174
    }
175
176
    /**
177
     * Returns the value of the "sizes" attribute corresponding to the configured class.
178
     */
179
    public static function getSizes(string $class, array $sizes = []): string
180
    {
181
        $result = '';
182
        $classArray = explode(' ', $class);
183
        foreach ($classArray as $class) {
184
            if (\array_key_exists($class, $sizes)) {
185
                $result = $sizes[$class] . ', ';
186
            }
187
        }
188
        if (!empty($result)) {
189
            return trim($result, ', ');
190
        }
191
192
        return $sizes['default'] ?? '100vw';
193
    }
194
195
    /**
196
     * Checks if an asset is an animated GIF.
197
     */
198
    public static function isAnimatedGif(Asset $asset): bool
199
    {
200
        // an animated GIF contains multiple "frames", with each frame having a header made up of:
201
        // 1. a static 4-byte sequence (\x00\x21\xF9\x04)
202
        // 2. 4 variable bytes
203
        // 3. a static 2-byte sequence (\x00\x2C)
204
        $count = preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', (string) $asset['content_source']);
205
206
        return $count > 1;
207
    }
208
209
    /**
210
     * Returns true if asset is a SVG.
211
     */
212
    public static function isSVG(Asset $asset): bool
213
    {
214
        return \in_array($asset['subtype'], ['image/svg', 'image/svg+xml']) || $asset['ext'] == 'svg';
215
    }
216
217
    /**
218
     * Returns SVG attributes.
219
     *
220
     * @return \SimpleXMLElement|false
221
     */
222
    public static function getSvgAttributes(Asset $asset)
223
    {
224
        if (!self::isSVG($asset)) {
225
            return false;
226
        }
227
228
        if (false === $xml = simplexml_load_string($asset['content_source'] ?? '')) {
229
            return false;
230
        }
231
232
        return $xml->attributes();
233
    }
234
}
235