1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* ImageOptimize plugin for Craft CMS |
4
|
|
|
* |
5
|
|
|
* Automatically optimize images after they've been transformed |
6
|
|
|
* |
7
|
|
|
* @link https://nystudio107.com |
|
|
|
|
8
|
|
|
* @copyright Copyright (c) 2017 nystudio107 |
|
|
|
|
9
|
|
|
*/ |
|
|
|
|
10
|
|
|
|
11
|
|
|
namespace nystudio107\imageoptimize\services; |
12
|
|
|
|
13
|
|
|
use Craft; |
14
|
|
|
use craft\base\Component; |
15
|
|
|
use craft\base\ElementInterface; |
|
|
|
|
16
|
|
|
use craft\base\Field; |
17
|
|
|
use craft\console\Application as ConsoleApplication; |
18
|
|
|
use craft\elements\Asset; |
19
|
|
|
use craft\errors\FsObjectNotFoundException; |
20
|
|
|
use craft\errors\InvalidFieldException; |
21
|
|
|
use craft\errors\SiteNotFoundException; |
22
|
|
|
use craft\helpers\Image; |
23
|
|
|
use craft\helpers\ImageTransforms as TransformHelper; |
24
|
|
|
use craft\helpers\Json; |
25
|
|
|
use craft\imagetransforms\ImageTransformer; |
26
|
|
|
use craft\models\FieldLayout; |
27
|
|
|
use craft\models\ImageTransform as AssetTransform; |
28
|
|
|
use craft\models\Volume; |
29
|
|
|
use craft\records\Element_SiteSettings as Element_SiteSettingsRecord; |
30
|
|
|
use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField; |
31
|
|
|
use nystudio107\imageoptimize\helpers\Image as ImageHelper; |
32
|
|
|
use nystudio107\imageoptimize\ImageOptimize; |
33
|
|
|
use nystudio107\imageoptimize\imagetransforms\CraftImageTransform; |
34
|
|
|
use nystudio107\imageoptimize\jobs\ResaveOptimizedImages; |
35
|
|
|
use nystudio107\imageoptimize\models\OptimizedImage; |
36
|
|
|
use nystudio107\imageoptimize\models\Settings; |
37
|
|
|
use Throwable; |
38
|
|
|
use yii\base\InvalidConfigException; |
39
|
|
|
use yii\db\Exception; |
40
|
|
|
use function in_array; |
41
|
|
|
|
42
|
|
|
/** |
|
|
|
|
43
|
|
|
* @author nystudio107 |
|
|
|
|
44
|
|
|
* @package ImageOptimize |
|
|
|
|
45
|
|
|
* @since 1.4.0 |
|
|
|
|
46
|
|
|
*/ |
|
|
|
|
47
|
|
|
class OptimizedImages extends Component |
48
|
|
|
{ |
49
|
|
|
// Constants |
50
|
|
|
// ========================================================================= |
51
|
|
|
|
52
|
|
|
// Public Properties |
53
|
|
|
// ========================================================================= |
54
|
|
|
|
55
|
|
|
// Public Methods |
56
|
|
|
// ========================================================================= |
57
|
|
|
|
58
|
|
|
/** |
|
|
|
|
59
|
|
|
* @param Asset $asset |
|
|
|
|
60
|
|
|
* @param array $variants |
|
|
|
|
61
|
|
|
* |
62
|
|
|
* @return OptimizedImage |
63
|
|
|
* @throws InvalidConfigException |
64
|
|
|
*/ |
65
|
|
|
public function createOptimizedImages(Asset $asset, array $variants = []): OptimizedImage |
66
|
|
|
{ |
67
|
|
|
Craft::beginProfile('createOptimizedImages', __METHOD__); |
68
|
|
|
if (empty($variants)) { |
69
|
|
|
/** @var ?Settings $settings */ |
|
|
|
|
70
|
|
|
$settings = ImageOptimize::$plugin->getSettings(); |
|
|
|
|
71
|
|
|
if ($settings) { |
|
|
|
|
72
|
|
|
$variants = $settings->defaultVariants; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$model = new OptimizedImage(); |
77
|
|
|
$this->populateOptimizedImageModel($asset, $variants, $model); |
78
|
|
|
Craft::endProfile('createOptimizedImages', __METHOD__); |
79
|
|
|
|
80
|
|
|
return $model; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
/** |
|
|
|
|
84
|
|
|
* @param Asset $asset |
|
|
|
|
85
|
|
|
* @param array $variants |
|
|
|
|
86
|
|
|
* @param OptimizedImage $model |
|
|
|
|
87
|
|
|
* @param bool $force |
|
|
|
|
88
|
|
|
* @throws InvalidConfigException |
|
|
|
|
89
|
|
|
*/ |
|
|
|
|
90
|
|
|
public function populateOptimizedImageModel(Asset $asset, array $variants, OptimizedImage $model, bool $force = false): void |
91
|
|
|
{ |
92
|
|
|
Craft::beginProfile('populateOptimizedImageModel', __METHOD__); |
93
|
|
|
/** @var Settings $settings */ |
|
|
|
|
94
|
|
|
$settings = ImageOptimize::$plugin->getSettings(); |
95
|
|
|
// Empty our the optimized image URLs |
96
|
|
|
$model->optimizedImageUrls = []; |
97
|
|
|
$model->optimizedWebPImageUrls = []; |
98
|
|
|
$model->variantSourceWidths = []; |
99
|
|
|
$model->placeholderWidth = 0; |
100
|
|
|
$model->placeholderHeight = 0; |
101
|
|
|
$model->stickyErrors = []; |
102
|
|
|
|
103
|
|
|
foreach ($variants as $variant) { |
104
|
|
|
$retinaSizes = ['1']; |
105
|
|
|
if (!empty($variant['retinaSizes'])) { |
106
|
|
|
$retinaSizes = $variant['retinaSizes']; |
107
|
|
|
} |
108
|
|
|
foreach ($retinaSizes as $retinaSize) { |
109
|
|
|
$finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format']; |
110
|
|
|
$variantFormat = $finalFormat; |
111
|
|
|
if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) { |
112
|
|
|
$variantFormat = empty($variant['format']) ? null : $variant['format']; |
113
|
|
|
} |
114
|
|
|
$variant['format'] = $variantFormat; |
115
|
|
|
// Only try the transform if it's possible |
116
|
|
|
if ((int)$asset->height > 0 |
117
|
|
|
&& Image::canManipulateAsImage($finalFormat) |
118
|
|
|
&& Image::canManipulateAsImage($asset->getExtension()) |
119
|
|
|
) { |
120
|
|
|
// Create the transform based on the variant |
121
|
|
|
/** @var AssetTransform $transform */ |
|
|
|
|
122
|
|
|
[$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, $retinaSize); |
123
|
|
|
// If they want to $force it, set `fileExists` = 0 in the transform index, then delete the transformed image |
124
|
|
|
if ($force) { |
125
|
|
|
$transformer = Craft::createObject(ImageTransformer::class); |
126
|
|
|
|
127
|
|
|
try { |
128
|
|
|
$index = $transformer->getTransformIndex($asset, $transform); |
129
|
|
|
$index->fileExists = false; |
130
|
|
|
$transformer->storeTransformIndexData($index); |
131
|
|
|
try { |
132
|
|
|
$transformer->deleteImageTransformFile($asset, $index); |
133
|
|
|
} catch (Throwable $exception) { |
|
|
|
|
134
|
|
|
} |
135
|
|
|
} catch (Throwable $e) { |
136
|
|
|
$msg = 'Failed to update transform: ' . $e->getMessage(); |
137
|
|
|
Craft::error($msg, __METHOD__); |
138
|
|
|
if (Craft::$app instanceof ConsoleApplication) { |
139
|
|
|
echo $msg . PHP_EOL; |
140
|
|
|
} |
141
|
|
|
// Add the error message to the stickyErrors for the model |
142
|
|
|
$model->stickyErrors[] = $msg; |
143
|
|
|
} |
144
|
|
|
} |
145
|
|
|
// Only create the image variant if it is not upscaled, or they are okay with it being up-scaled |
146
|
|
|
if (($asset->width >= $transform->width && $asset->height >= $transform->height) |
147
|
|
|
|| $settings->allowUpScaledImageVariants |
148
|
|
|
) { |
149
|
|
|
$this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
150
|
|
|
} |
151
|
|
|
} else { |
152
|
|
|
$canManipulate = Image::canManipulateAsImage($asset->getExtension()); |
153
|
|
|
$msg = 'Could not create transform for: ' . $asset->title |
154
|
|
|
. ' - Final format: ' . $finalFormat |
155
|
|
|
. ' - Element extension: ' . $asset->getExtension() |
156
|
|
|
. ' - canManipulateAsImage: ' . $canManipulate; |
157
|
|
|
Craft::error( |
158
|
|
|
$msg, |
159
|
|
|
__METHOD__ |
160
|
|
|
); |
161
|
|
|
if (Craft::$app instanceof ConsoleApplication) { |
162
|
|
|
echo $msg . PHP_EOL; |
163
|
|
|
} |
164
|
|
|
if ($canManipulate) { |
165
|
|
|
// Add the error message to the stickyErrors for the model |
166
|
|
|
$model->stickyErrors[] = $msg; |
167
|
|
|
} |
168
|
|
|
} |
169
|
|
|
} |
170
|
|
|
} |
171
|
|
|
|
172
|
|
|
// If no image variants were created, populate it with the image itself |
173
|
|
|
if (empty($model->optimizedImageUrls)) { |
174
|
|
|
$finalFormat = $asset->getExtension(); |
175
|
|
|
if ((int)$asset->height > 0 |
176
|
|
|
&& Image::canManipulateAsImage($finalFormat) |
177
|
|
|
) { |
178
|
|
|
$variant = [ |
179
|
|
|
'width' => $asset->width, |
180
|
|
|
'useAspectRatio' => false, |
181
|
|
|
'aspectRatioX' => $asset->width, |
182
|
|
|
'aspectRatioY' => $asset->height, |
183
|
|
|
'retinaSizes' => ['1'], |
184
|
|
|
'quality' => 0, |
185
|
|
|
'format' => $finalFormat, |
186
|
|
|
]; |
187
|
|
|
[$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, 1); |
188
|
|
|
$this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio); |
189
|
|
|
} else { |
190
|
|
|
$canManipulate = Image::canManipulateAsImage($asset->getExtension()); |
191
|
|
|
$msg = 'Could not create transform for: ' . $asset->title |
192
|
|
|
. ' - Final format: ' . $finalFormat |
193
|
|
|
. ' - Element extension: ' . $asset->getExtension() |
194
|
|
|
. ' - canManipulateAsImage: ' . $canManipulate; |
195
|
|
|
Craft::error( |
196
|
|
|
$msg, |
197
|
|
|
__METHOD__ |
198
|
|
|
); |
199
|
|
|
if ($canManipulate) { |
200
|
|
|
// Add the error message to the stickyErrors for the model |
201
|
|
|
$model->stickyErrors[] = $msg; |
202
|
|
|
} |
203
|
|
|
} |
204
|
|
|
} |
205
|
|
|
Craft::endProfile('populateOptimizedImageModel', __METHOD__); |
206
|
|
|
} |
207
|
|
|
|
208
|
|
|
/** |
209
|
|
|
* Should variants be created for the given OptimizedImages field and the Asset? |
210
|
|
|
* |
211
|
|
|
* @param $field |
|
|
|
|
212
|
|
|
* @param $asset |
|
|
|
|
213
|
|
|
* @return bool |
|
|
|
|
214
|
|
|
*/ |
215
|
|
|
public function shouldCreateVariants($field, $asset): bool |
216
|
|
|
{ |
217
|
|
|
$createVariants = true; |
218
|
|
|
Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__); |
|
|
|
|
219
|
|
|
// See if we're ignoring files in this dir |
220
|
|
|
if (!empty($field->fieldVolumeSettings)) { |
221
|
|
|
foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) { |
222
|
|
|
if ($asset->getVolume()->handle === $volumeHandle) { |
223
|
|
|
if (is_string($subfolders) && $subfolders === '*') { |
224
|
|
|
$createVariants = true; |
225
|
|
|
Craft::info("Matched '*' wildcard ", __METHOD__); |
226
|
|
|
} else { |
227
|
|
|
$createVariants = false; |
228
|
|
|
if (is_array($subfolders)) { |
229
|
|
|
foreach ($subfolders as $subfolder) { |
230
|
|
|
$folder = $asset->getFolder(); |
231
|
|
|
while ($folder !== null && !$createVariants) { |
232
|
|
|
if ($folder->uid === $subfolder || $folder->name === $subfolder) { |
233
|
|
|
Craft::info('Matched subfolder uid: ' . print_r($subfolder, true), __METHOD__); |
|
|
|
|
234
|
|
|
$createVariants = true; |
235
|
|
|
} else { |
236
|
|
|
$folder = $folder->getParent(); |
237
|
|
|
} |
238
|
|
|
} |
239
|
|
|
} |
240
|
|
|
} |
241
|
|
|
} |
242
|
|
|
} |
243
|
|
|
} |
244
|
|
|
} |
245
|
|
|
// See if we should ignore this type of file |
246
|
|
|
$sourceType = $asset->getMimeType(); |
247
|
|
|
if (!empty($field->ignoreFilesOfType) && $sourceType !== null) { |
248
|
|
|
$ignoreTypes = array_values($field->ignoreFilesOfType); |
249
|
|
|
// If `image/svg` is being ignored, add `image/svg+xml` to the mime types to ignore as well |
250
|
|
|
if (in_array('image/svg', $ignoreTypes, false)) { |
251
|
|
|
$ignoreTypes[] = 'image/svg+xml'; |
252
|
|
|
} |
253
|
|
|
if (in_array($sourceType, $ignoreTypes, false)) { |
254
|
|
|
$createVariants = false; |
255
|
|
|
} |
256
|
|
|
} |
257
|
|
|
return $createVariants; |
258
|
|
|
} |
259
|
|
|
|
260
|
|
|
/** |
|
|
|
|
261
|
|
|
* @param Field $field |
|
|
|
|
262
|
|
|
* @param ElementInterface $asset |
|
|
|
|
263
|
|
|
* @param bool $force |
|
|
|
|
264
|
|
|
* |
265
|
|
|
* @throws Exception |
266
|
|
|
* @throws InvalidConfigException |
267
|
|
|
* @throws InvalidFieldException |
268
|
|
|
*/ |
|
|
|
|
269
|
|
|
public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset, bool $force = false): void |
270
|
|
|
{ |
271
|
|
|
/** @var Asset $asset */ |
|
|
|
|
272
|
|
|
if ($asset instanceof Asset && $field instanceof OptimizedImagesField) { |
273
|
|
|
$createVariants = $this->shouldCreateVariants($field, $asset); |
274
|
|
|
// Create a new OptimizedImage model and populate it |
275
|
|
|
$model = new OptimizedImage(); |
276
|
|
|
// Empty our the optimized image URLs |
277
|
|
|
$model->optimizedImageUrls = []; |
278
|
|
|
$model->optimizedWebPImageUrls = []; |
279
|
|
|
$model->variantSourceWidths = []; |
280
|
|
|
$model->placeholderWidth = 0; |
281
|
|
|
$model->placeholderHeight = 0; |
282
|
|
|
if ($createVariants) { |
283
|
|
|
$this->populateOptimizedImageModel( |
284
|
|
|
$asset, |
285
|
|
|
$field->variants, |
286
|
|
|
$model, |
287
|
|
|
$force |
288
|
|
|
); |
289
|
|
|
} |
290
|
|
|
// Save the changed data directly into the elements_sites.content table |
291
|
|
|
if ($field->handle !== null) { |
292
|
|
|
$asset->setFieldValue($field->handle, $field->serializeValue($model, $asset)); |
293
|
|
|
$fieldLayout = $asset->getFieldLayout(); |
294
|
|
|
$siteSettingsRecords = Element_SiteSettingsRecord::findAll([ |
|
|
|
|
295
|
|
|
'elementId' => $asset->id, |
296
|
|
|
]); |
|
|
|
|
297
|
|
|
// Update it for all of the sites |
298
|
|
|
foreach ($siteSettingsRecords as $siteSettingsRecord) { |
299
|
|
|
// Set the field values |
300
|
|
|
if ($fieldLayout) { |
301
|
|
|
$content = Json::decodeIfJson($siteSettingsRecord->content); |
302
|
|
|
if (!is_array($content)) { |
303
|
|
|
$content = []; |
304
|
|
|
} |
305
|
|
|
$content[$field->layoutElement->uid] = $field->serializeValue($asset->getFieldValue($field->handle), $asset); |
306
|
|
|
$siteSettingsRecord->content = $content; |
307
|
|
|
// Save the site settings record |
308
|
|
|
if (!$siteSettingsRecord->save(false)) { |
309
|
|
|
Craft::error('Couldn’t save elements’ site settings record.', __METHOD__); |
310
|
|
|
} |
311
|
|
|
} |
312
|
|
|
} |
313
|
|
|
} |
314
|
|
|
} |
315
|
|
|
} |
316
|
|
|
|
317
|
|
|
/** |
318
|
|
|
* Re-save all the assets in all the volumes |
319
|
|
|
* |
320
|
|
|
* @param ?int $fieldId only for this specific id |
321
|
|
|
* @param bool $force Should image variants be forced to be recreated? |
|
|
|
|
322
|
|
|
* |
323
|
|
|
* @throws InvalidConfigException |
324
|
|
|
*/ |
|
|
|
|
325
|
|
|
public function resaveAllVolumesAssets(?int $fieldId = null, bool $force = false): void |
326
|
|
|
{ |
327
|
|
|
$volumes = Craft::$app->getVolumes()->getAllVolumes(); |
328
|
|
|
foreach ($volumes as $volume) { |
329
|
|
|
$this->resaveVolumeAssets($volume, $fieldId, $force); |
330
|
|
|
} |
331
|
|
|
} |
332
|
|
|
|
333
|
|
|
/** |
334
|
|
|
* Re-save all the Asset elements in the Volume $volume that have an |
335
|
|
|
* OptimizedImages field in the FieldLayout |
336
|
|
|
* |
337
|
|
|
* @param Volume $volume for this volume |
|
|
|
|
338
|
|
|
* @param ?int $fieldId only for this specific id |
|
|
|
|
339
|
|
|
* @param bool $force Should image variants be forced to be recreated? |
|
|
|
|
340
|
|
|
*/ |
|
|
|
|
341
|
|
|
public function resaveVolumeAssets(Volume $volume, ?int $fieldId = null, bool $force = false): void |
342
|
|
|
{ |
343
|
|
|
$needToReSave = false; |
344
|
|
|
/** @var ?FieldLayout $fieldLayout */ |
|
|
|
|
345
|
|
|
$fieldLayout = $volume->getFieldLayout(); |
346
|
|
|
// Loop through the fields in the layout to see if there is an OptimizedImages field |
347
|
|
|
if ($fieldLayout) { |
348
|
|
|
$fields = $fieldLayout->getCustomFields(); |
349
|
|
|
foreach ($fields as $field) { |
350
|
|
|
if ($field instanceof OptimizedImagesField) { |
351
|
|
|
$needToReSave = true; |
352
|
|
|
} |
353
|
|
|
} |
354
|
|
|
} |
355
|
|
|
if ($needToReSave) { |
356
|
|
|
try { |
357
|
|
|
$siteId = Craft::$app->getSites()->getPrimarySite()->id; |
358
|
|
|
} catch (SiteNotFoundException $e) { |
359
|
|
|
$siteId = 0; |
360
|
|
|
Craft::error( |
361
|
|
|
'Failed to get primary site: ' . $e->getMessage(), |
362
|
|
|
__METHOD__ |
363
|
|
|
); |
364
|
|
|
} |
365
|
|
|
|
366
|
|
|
$queue = Craft::$app->getQueue(); |
367
|
|
|
$jobId = $queue->push(new ResaveOptimizedImages([ |
|
|
|
|
368
|
|
|
'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]), |
369
|
|
|
'criteria' => [ |
370
|
|
|
'siteId' => $siteId, |
371
|
|
|
'volumeId' => $volume->id, |
372
|
|
|
'status' => null, |
373
|
|
|
], |
374
|
|
|
'fieldId' => $fieldId, |
375
|
|
|
'force' => $force, |
376
|
|
|
])); |
|
|
|
|
377
|
|
|
Craft::debug( |
378
|
|
|
Craft::t( |
379
|
|
|
'image-optimize', |
380
|
|
|
'Started resaveVolumeAssets queue job id: {jobId}', |
381
|
|
|
[ |
382
|
|
|
'jobId' => $jobId, |
383
|
|
|
] |
384
|
|
|
), |
385
|
|
|
__METHOD__ |
386
|
|
|
); |
387
|
|
|
} |
388
|
|
|
} |
389
|
|
|
|
390
|
|
|
/** |
391
|
|
|
* Re-save an individual asset |
392
|
|
|
* |
393
|
|
|
* @param int $id |
|
|
|
|
394
|
|
|
* @param bool $force Should image variants be forced to be recreated? |
395
|
|
|
*/ |
|
|
|
|
396
|
|
|
public function resaveAsset(int $id, bool $force = false): void |
397
|
|
|
{ |
398
|
|
|
$queue = Craft::$app->getQueue(); |
399
|
|
|
$jobId = $queue->push(new ResaveOptimizedImages([ |
|
|
|
|
400
|
|
|
'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]), |
401
|
|
|
'criteria' => [ |
402
|
|
|
'id' => $id, |
403
|
|
|
'status' => null, |
404
|
|
|
], |
405
|
|
|
'force' => $force, |
406
|
|
|
])); |
|
|
|
|
407
|
|
|
Craft::debug( |
408
|
|
|
Craft::t( |
409
|
|
|
'image-optimize', |
410
|
|
|
'Started resaveAsset queue job id: {jobId} Element id: {elementId}', |
411
|
|
|
[ |
412
|
|
|
'elementId' => $id, |
413
|
|
|
'jobId' => $jobId, |
414
|
|
|
] |
415
|
|
|
), |
416
|
|
|
__METHOD__ |
417
|
|
|
); |
418
|
|
|
} |
419
|
|
|
|
420
|
|
|
/** |
421
|
|
|
* Create an optimized SVG data uri |
422
|
|
|
* See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris |
423
|
|
|
* |
424
|
|
|
* @param string $uri |
|
|
|
|
425
|
|
|
* |
426
|
|
|
* @return string |
427
|
|
|
*/ |
428
|
|
|
public function encodeOptimizedSVGDataUri(string $uri): string |
429
|
|
|
{ |
430
|
|
|
// First, uri encode everything |
431
|
|
|
$uri = rawurlencode($uri); |
432
|
|
|
$replacements = [ |
433
|
|
|
// remove newlines |
434
|
|
|
'/%0A/' => '', |
435
|
|
|
// put equals signs back in |
436
|
|
|
'/%3D/' => '=', |
437
|
|
|
// put colons back in |
438
|
|
|
'/%3A/' => ':', |
439
|
|
|
// put slashes back in |
440
|
|
|
'/%2F/' => '/', |
441
|
|
|
// replace quotes with apostrophes (may break certain SVGs) |
442
|
|
|
'/%22/' => "'", |
443
|
|
|
]; |
444
|
|
|
foreach ($replacements as $pattern => $replacement) { |
445
|
|
|
$uri = preg_replace($pattern, $replacement, $uri); |
446
|
|
|
} |
447
|
|
|
|
448
|
|
|
return $uri; |
449
|
|
|
} |
450
|
|
|
|
451
|
|
|
// Protected Methods |
452
|
|
|
// ========================================================================= |
453
|
|
|
|
454
|
|
|
/** |
|
|
|
|
455
|
|
|
* @param Asset $element |
|
|
|
|
456
|
|
|
* @param OptimizedImage $model |
|
|
|
|
457
|
|
|
* @param $aspectRatio |
|
|
|
|
458
|
|
|
*/ |
|
|
|
|
459
|
|
|
protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio): void |
460
|
|
|
{ |
461
|
|
|
Craft::beginProfile('generatePlaceholders', __METHOD__); |
462
|
|
|
Craft::info( |
463
|
|
|
'generatePlaceholders for: ' . print_r($model, true), |
|
|
|
|
464
|
|
|
__METHOD__ |
465
|
|
|
); |
466
|
|
|
/** @var Settings $settings */ |
|
|
|
|
467
|
|
|
$settings = ImageOptimize::$plugin->getSettings(); |
468
|
|
|
if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) { |
469
|
|
|
$placeholder = ImageOptimize::$plugin->placeholder; |
470
|
|
|
if ($element->focalPoint) { |
471
|
|
|
$position = $element->getFocalPoint(); |
472
|
|
|
} else { |
473
|
|
|
$position = 'center-center'; |
474
|
|
|
} |
475
|
|
|
$tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position); |
476
|
|
|
if (!empty($tempPath)) { |
477
|
|
|
// Generate our placeholder image |
478
|
|
|
$model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position); |
479
|
|
|
// Generate the color palette for the image |
480
|
|
|
if ($settings->createColorPalette) { |
481
|
|
|
$model->colorPalette = $placeholder->generateColorPalette($tempPath); |
482
|
|
|
$model->lightness = $placeholder->calculateLightness($model->colorPalette); |
|
|
|
|
483
|
|
|
} |
484
|
|
|
// Generate the Potrace SVG |
485
|
|
|
if ($settings->createPlaceholderSilhouettes) { |
486
|
|
|
$model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath); |
487
|
|
|
} |
488
|
|
|
// Get rid of our placeholder image |
489
|
|
|
@unlink($tempPath); |
|
|
|
|
490
|
|
|
} |
491
|
|
|
} |
492
|
|
|
Craft::endProfile('generatePlaceholders', __METHOD__); |
493
|
|
|
} |
494
|
|
|
|
495
|
|
|
/** |
|
|
|
|
496
|
|
|
* @param Asset $asset |
|
|
|
|
497
|
|
|
* @param $variant |
|
|
|
|
498
|
|
|
* @param $retinaSize |
|
|
|
|
499
|
|
|
* |
500
|
|
|
* @return array |
501
|
|
|
* @throws FsObjectNotFoundException |
502
|
|
|
*/ |
503
|
|
|
protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array |
504
|
|
|
{ |
505
|
|
|
/** @var Settings $settings */ |
|
|
|
|
506
|
|
|
$settings = ImageOptimize::$plugin->getSettings(); |
507
|
|
|
$transform = new AssetTransform(); |
508
|
|
|
$transform->format = $variant['format'] ?? null; |
509
|
|
|
// Handle animate .gif images by never changing the format |
510
|
|
|
$images = Craft::$app->getImages(); |
511
|
|
|
if ($asset->extension === 'gif' && !$images->getIsGd()) { |
512
|
|
|
$imageSource = TransformHelper::getLocalImageSource($asset); |
513
|
|
|
try { |
514
|
|
|
if (ImageHelper::getIsAnimatedGif($imageSource)) { |
515
|
|
|
$transform->format = null; |
516
|
|
|
} |
517
|
|
|
} catch (\Exception $e) { |
518
|
|
|
Craft::error($e->getMessage(), __METHOD__); |
519
|
|
|
} |
520
|
|
|
} |
521
|
|
|
$useAspectRatio = $variant['useAspectRatio'] ?? false; |
522
|
|
|
if ($useAspectRatio) { |
523
|
|
|
$aspectRatio = (float)$variant['aspectRatioX'] / (float)$variant['aspectRatioY']; |
524
|
|
|
} else { |
525
|
|
|
$aspectRatio = (float)$asset->width / (float)$asset->height; |
526
|
|
|
} |
527
|
|
|
$width = (int)$variant['width'] * (int)$retinaSize; |
528
|
|
|
$transform->width = $width; |
529
|
|
|
$transform->height = (int)($width / $aspectRatio); |
530
|
|
|
// Image quality |
531
|
|
|
$quality = (int)($variant['quality'] ?? null); |
532
|
|
|
if (empty($quality)) { |
533
|
|
|
$quality = null; |
534
|
|
|
} |
535
|
|
|
if ($quality !== null && $settings->lowerQualityRetinaImageVariants && $retinaSize != '1') { |
536
|
|
|
$quality = (int)($quality * (1.5 / (int)$retinaSize)); |
537
|
|
|
} |
538
|
|
|
$transform->quality = $quality; |
539
|
|
|
// Interlaced (progressive JPEGs or interlaced PNGs) |
540
|
|
|
if (property_exists($transform, 'interlace')) { |
541
|
|
|
$transform->interlace = 'line'; |
542
|
|
|
} |
543
|
|
|
|
544
|
|
|
return [$transform, $aspectRatio]; |
545
|
|
|
} |
546
|
|
|
|
547
|
|
|
/** |
|
|
|
|
548
|
|
|
* @param Asset $asset |
|
|
|
|