-
Notifications
You must be signed in to change notification settings - Fork 611
/
Svg.php
265 lines (220 loc) · 8.18 KB
/
Svg.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\image;
use Craft;
use craft\base\Image;
use craft\errors\ImageException;
use craft\helpers\FileHelper;
use craft\helpers\Image as ImageHelper;
/**
* Svg class is used for SVG file manipulations.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Svg extends Image
{
public const SVG_WIDTH_RE = '/(<svg[^>]*\swidth=")([\d\.]+)([a-z]*)"/i';
public const SVG_HEIGHT_RE = '/(<svg[^>]*\sheight=")([\d\.]+)([a-z]*)"/i';
public const SVG_VIEWBOX_RE = '/(<svg[^>]*\sviewBox=")(-?[\d.]+(?:,|\s)-?[\d.]+(?:,|\s)-?([\d.]+)(?:,|\s)(-?[\d.]+))"/i';
public const SVG_ASPECT_RE = '/(<svg[^>]*\spreserveAspectRatio=")([a-z]+\s[a-z]+)"/i';
public const SVG_TAG_RE = '/<svg/i';
public const SVG_CLEANUP_WIDTH_RE = '/(<svg[^>]*\s)width="[\d\.]+%"/i';
public const SVG_CLEANUP_HEIGHT_RE = '/(<svg[^>]*\s)height="[\d\.]+%"/i';
/**
* @var string|null
*/
private ?string $_svgContent = null;
/**
* @var int|null
*/
private ?int $_height = null;
/**
* @var int|null
*/
private ?int $_width = null;
/**
* @inheritdoc
*/
public function getWidth(): int
{
return $this->_width;
}
/**
* @inheritdoc
*/
public function getHeight(): int
{
return $this->_height;
}
/**
* @inheritdoc
*/
public function getExtension(): string
{
return 'svg';
}
/**
* @inheritdoc
*/
public function loadImage(string $path): self
{
if (!is_file($path)) {
Craft::error('Tried to load an image at ' . $path . ', but the file does not exist.', __METHOD__);
throw new ImageException(Craft::t('app', 'No file exists at the given path.'));
}
$svg = file_get_contents($path);
if ($svg === false) {
Craft::error('Tried to read the SVG contents at ' . $path . ', but could not.', __METHOD__);
throw new ImageException(Craft::t('app', 'Could not read SVG contents.'));
}
[$width, $height] = ImageHelper::parseSvgSize($svg);
// If the size is defined by viewbox only, add in width and height attributes
if (!preg_match(self::SVG_WIDTH_RE, $svg) && preg_match(self::SVG_HEIGHT_RE, $svg)) {
$svg = preg_replace(self::SVG_TAG_RE,
"<svg width=\"{$width}px\" height=\"{$height}px\" ", $svg);
}
$this->_height = $height;
$this->_width = $width;
$this->_svgContent = $svg;
return $this;
}
/**
* @inheritdoc
*/
public function crop(int $x1, int $x2, int $y1, int $y2): self
{
$width = $x2 - $x1;
$height = $y2 - $y1;
// If the SVG had a viewbox, it might have been scaled already.
if (preg_match(self::SVG_VIEWBOX_RE, $this->_svgContent,
$viewboxMatch)) {
$viewBoxXFactor = $this->getWidth() / round($viewboxMatch[3]);
$viewBoxYFactor = $this->getHeight() / round($viewboxMatch[4]);
} else {
$viewBoxXFactor = 1;
$viewBoxYFactor = 1;
}
$this->resize($width, $height);
$x1 /= $viewBoxXFactor;
$y1 /= $viewBoxYFactor;
$width /= $viewBoxXFactor;
$height /= $viewBoxYFactor;
$value = "$x1 $y1 $width $height";
// Add/modify the viewbox to crop the image.
if (preg_match(self::SVG_VIEWBOX_RE, $this->_svgContent)) {
$this->_svgContent = preg_replace(self::SVG_VIEWBOX_RE,
"\${1}$value\"", $this->_svgContent);
} else {
$this->_svgContent = preg_replace(self::SVG_TAG_RE,
"<svg viewBox=\"$value\"", $this->_svgContent);
}
return $this;
}
/**
* @inheritdoc
*/
public function scaleToFit(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true): self
{
$this->normalizeDimensions($targetWidth, $targetHeight);
if ($scaleIfSmaller || $this->getWidth() > $targetWidth || $this->getHeight() > $targetHeight) {
$factor = max($this->getWidth() / $targetWidth,
$this->getHeight() / $targetHeight);
$this->resize(round($this->getWidth() / $factor), round($this->getHeight() / $factor));
}
return $this;
}
/**
* @inheritdoc
*/
public function scaleAndCrop(?int $targetWidth, ?int $targetHeight, bool $scaleIfSmaller = true, array|string $cropPosition = 'center-center'): self
{
// TODO If we encounter a focal point, rasterize and crop with focal.
if (is_array($cropPosition)) {
throw new ImageException(Craft::t('app', 'Currently SVG images do not support focal point.'));
}
$this->normalizeDimensions($targetWidth, $targetHeight);
if ($scaleIfSmaller || $this->getWidth() > $targetWidth || $this->getHeight() > $targetHeight) {
// Scale first.
$this->resize($targetWidth, $targetHeight);
// Reverse the components
$cropPositions = implode('-', array_reverse(explode('-', $cropPosition)));
$value = 'x' . strtr($cropPositions, [
'left' => 'Min',
'center' => 'Mid',
'right' => 'Max',
'top' => 'Min',
'bottom' => 'Max',
'-' => 'Y',
]) . ' slice';
// Add/modify aspect ratio information
if (preg_match(self::SVG_ASPECT_RE, $this->_svgContent)) {
$this->_svgContent = preg_replace(self::SVG_ASPECT_RE,
"\${1}$value\"", $this->_svgContent);
} else {
$this->_svgContent = preg_replace(self::SVG_TAG_RE,
"<svg preserveAspectRatio=\"$value\"",
$this->_svgContent);
}
}
return $this;
}
/**
* @inheritdoc
*/
public function resize(?int $targetWidth, ?int $targetHeight): self
{
$this->normalizeDimensions($targetWidth, $targetHeight);
if (preg_match(self::SVG_WIDTH_RE, $this->_svgContent) && preg_match(self::SVG_HEIGHT_RE, $this->_svgContent)) {
$this->_svgContent = preg_replace(self::SVG_WIDTH_RE, "\${1}{$targetWidth}px\"", $this->_svgContent);
$this->_svgContent = preg_replace(self::SVG_HEIGHT_RE, "\${1}{$targetHeight}px\"", $this->_svgContent);
} else {
// In case the root element has dimension attributes set with percentage,
// weed them out so we don't duplicate them.
$this->_svgContent = preg_replace(self::SVG_CLEANUP_WIDTH_RE, '${1}', $this->_svgContent);
$this->_svgContent = preg_replace(self::SVG_CLEANUP_HEIGHT_RE, '${1}', $this->_svgContent);
$this->_svgContent = preg_replace(self::SVG_TAG_RE, "<svg width=\"{$targetWidth}px\" height=\"{$targetHeight}px\"", $this->_svgContent);
}
// If viewbox does not exist, add it to retain the scale.
if (!preg_match(static::SVG_VIEWBOX_RE, $this->_svgContent)) {
$viewBox = "0 0 $this->_width $this->_height";
$this->_svgContent = preg_replace(static::SVG_TAG_RE, "<svg viewBox=\"$viewBox\"", $this->_svgContent);
}
$this->_width = $targetWidth;
$this->_height = $targetHeight;
return $this;
}
/**
* @inheritdoc
*/
public function saveAs(string $targetPath, bool $autoQuality = false): bool
{
if (pathinfo($targetPath, PATHINFO_EXTENSION) === 'svg') {
FileHelper::writeToFile($targetPath, $this->_svgContent);
} else {
throw new ImageException(Craft::t('app',
'Manipulated SVG image rasterizing is unreliable. See \craft\services\Images::loadImage()'));
}
return true;
}
/**
* Returns the SVG string.
*
* @return string
*/
public function getSvgString(): string
{
return $this->_svgContent;
}
/**
* @inheritdoc
*/
public function getIsTransparent(): bool
{
return true;
}
}