-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathImageManipulation.php
1238 lines (1115 loc) · 38.6 KB
/
ImageManipulation.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\Assets;
use InvalidArgumentException;
use LogicException;
use Psr\Log\LoggerInterface;
use SilverStripe\Assets\Conversion\FileConverterException;
use SilverStripe\Assets\Conversion\FileConverterManager;
use SilverStripe\Assets\FilenameParsing\AbstractFileIDHelper;
use SilverStripe\Assets\Storage\AssetContainer;
use SilverStripe\Assets\Storage\AssetStore;
use SilverStripe\Assets\Storage\DBFile;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorNotFoundException;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\View\AttributesHTML;
use SilverStripe\View\HTML;
/**
* Provides image manipulation functionality.
* Provides limited thumbnail generation functionality for non-image files.
* Should only be applied to implementors of AssetContainer
*
* Allows raw images to be resampled via Resampled()
*
* Image scaling manipluations, including:
* - Fit()
* - FitMax()
* - ScaleWidth()
* - ScaleMaxWidth()
* - ScaleHeight()
* - ScaleMaxHeight()
* - ResizedImage()
*
* Image cropping manipulations, including:
* - CropHeight()
* - CropWidth()
* - Fill()
* - FillMax()
*
* Thumbnail generation methods including:
* - Icon()
* - CMSThumbnail()
*
* Other manipulations that do not create variants:
* - LazyLoad()
*
* @mixin AssetContainer
*/
trait ImageManipulation
{
use AttributesHTML;
/**
* @var Image_Backend
*/
protected $imageBackend;
/**
* If image resizes are allowed
*
* @var bool
*/
protected $allowGeneration = true;
/**
* Set whether image resizes are allowed
*
* @param bool $allow
* @return $this
*/
public function setAllowGeneration($allow)
{
$this->allowGeneration = $allow;
return $this;
}
/**
* Check if resizes are allowed
*
* @return bool
*/
public function getAllowGeneration()
{
return $this->allowGeneration;
}
/**
* Return clone of self which promises to only return existing thumbnails
*
* @return DBFile
*/
public function existingOnly()
{
$value = [
'Filename' => $this->getFilename(),
'Variant' => $this->getVariant(),
'Hash' => $this->getHash()
];
/** @var DBFile $file */
$file = DBField::create_field('DBFile', $value);
$file->setAllowGeneration(false);
return $file;
}
/**
* @return string Data from the file in this container
*/
abstract public function getString();
/**
* @return resource Data stream to the asset in this container
*/
abstract public function getStream();
/**
* @param bool $grant Ensures that the url for any protected assets is granted for the current user.
* @return string public url to the asset in this container
*/
abstract public function getURL($grant = true);
/**
* @return string The absolute URL to the asset in this container
*/
abstract public function getAbsoluteURL();
/**
* Get metadata for this file
*
* @return array|null File information
*/
abstract public function getMetaData();
/**
* Get mime type
*
* @return string Mime type for this file
*/
abstract public function getMimeType();
/**
* Return file size in bytes.
*
* @return int
*/
abstract public function getAbsoluteSize();
/**
* Determine if this container has a valid value
*
* @return bool Flag as to whether the file exists
*/
abstract public function exists();
/**
* Get value of filename
*
* @return string
*/
abstract public function getFilename();
/**
* Get value of hash
*
* @return string
*/
abstract public function getHash();
/**
* Get value of variant
*
* @return string
*/
abstract public function getVariant();
/**
* Determine if a valid non-empty image exists behind this asset
*
* @return bool
*/
abstract public function getIsImage();
/**
* Force all images to resample in all cases
* Off by default, as this can be resource intensive to apply to multiple images simultaneously.
*
* @config
* @var bool
*/
private static $force_resample = false;
/**
* @config
* @var int The width of an image thumbnail in a strip.
*/
private static $strip_thumbnail_width = 50;
/**
* @config
* @var int The height of an image thumbnail in a strip.
*/
private static $strip_thumbnail_height = 50;
/**
* The width of an image thumbnail in the CMS.
*
* @config
* @var int
*/
private static $cms_thumbnail_width = 100;
/**
* The height of an image thumbnail in the CMS.
*
* @config
* @var int
*/
private static $cms_thumbnail_height = 100;
/**
* The width of an image preview in the Asset section
*
* @config
* @var int
*/
private static $asset_preview_width = 930; // max for mobile full-width
/**
* The height of an image preview in the Asset section
*
* @config
* @var int
*/
private static $asset_preview_height = 336;
/**
* Fit image to specified dimensions and fill leftover space with a solid colour (default white). Use in
* templates with $Pad.
*
* @param int $width The width to size to
* @param int $height The height to size to
* @param string $backgroundColor
* @param int $transparencyPercent Level of transparency
* @return AssetContainer
*/
public function Pad($width, $height, $backgroundColor = 'FFFFFF', $transparencyPercent = 0)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $width, $height, $backgroundColor, $transparencyPercent);
return $this->manipulateImage(
$variant,
function (Image_Backend $backend) use ($width, $height, $backgroundColor, $transparencyPercent) {
if ($backend->getWidth() === $width && $backend->getHeight() === $height) {
return $this;
}
return $backend->paddedResize($width, $height, $backgroundColor, $transparencyPercent);
}
);
}
/**
* Forces the image to be resampled, if possible
*
* @return AssetContainer
*/
public function Resampled()
{
// If image is already resampled, return self reference
$variant = $this->getVariant();
if ($variant) {
return $this;
}
// Resample, but fallback to original object
$result = $this->manipulateImage(__FUNCTION__, function (Image_Backend $backend) {
return $backend;
});
if ($result) {
return $result;
}
return $this;
}
/**
* Update the url to point to a resampled version if forcing
*
* @param string $url
*/
public function updateURL(&$url)
{
// Skip if resampling is off, or is already resampled, or is not an image
if (!Config::inst()->get(get_class($this), 'force_resample') || $this->getVariant() || !$this->getIsImage()) {
return;
}
// Attempt to resample
$resampled = $this->Resampled();
if (!$resampled) {
return;
}
// Only update if resampled file is a smaller file size
if ($resampled->getAbsoluteSize() < $this->getAbsoluteSize()) {
$url = $resampled->getURL(false);
}
}
/**
* Generate a resized copy of this image with the given width & height.
* This can be used in templates with $ResizedImage but should be avoided,
* as it's the only image manipulation function which can skew an image.
*
* @param int $width Width to resize to
* @param int $height Height to resize to
* @return AssetContainer
*/
public function ResizedImage($width, $height)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $width, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height) {
if ($backend->getWidth() === $width && $backend->getHeight() === $height) {
return $this;
}
return $backend->resize($width, $height);
});
}
/**
* Scale image proportionally to fit within the specified bounds
*
* @param int $width The width to size within
* @param int $height The height to size within
* @return AssetContainer
*/
public function Fit($width, $height)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
// Item must be regenerated
$variant = $this->variantName(__FUNCTION__, $width, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height) {
// Check if image is already sized to the correct dimension
$currentWidth = $backend->getWidth();
$currentHeight = $backend->getHeight();
if (!$currentWidth || !$currentHeight) {
return null;
}
$widthRatio = $width / $currentWidth;
$heightRatio = $height / $currentHeight;
if ($widthRatio < $heightRatio) {
// Target is higher aspect ratio than image, so check width
if ($currentWidth === $width) {
return $this;
}
} else {
// Target is wider or same aspect ratio as image, so check height
if ($currentHeight === $height) {
return $this;
}
}
return $backend->resizeRatio($width, $height);
});
}
/**
* Proportionally scale down this image if it is wider or taller than the specified dimensions.
* Similar to Fit but without up-sampling. Use in templates with $FitMax.
*
* @uses ScalingManipulation::Fit()
* @param int $width The maximum width of the output image
* @param int $height The maximum height of the output image
* @return AssetContainer
*/
public function FitMax($width, $height)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $width, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height) {
// Check if image is already sized to the correct dimension
$currentWidth = $backend->getWidth();
$currentHeight = $backend->getHeight();
if (!$currentWidth || !$currentHeight) {
return null;
}
// Check if inside bounds
if ($currentWidth <= $width && $currentHeight <= $height) {
return $this;
}
$widthRatio = $width / $currentWidth;
$heightRatio = $height / $currentHeight;
if ($widthRatio < $heightRatio) {
// Target is higher aspect ratio than image, so check width
if ($currentWidth === $width) {
return $this;
}
} else {
// Target is wider or same aspect ratio as image, so check height
if ($currentHeight === $height) {
return $this;
}
}
return $backend->resizeRatio($width, $height);
});
}
/**
* Scale image proportionally by width. Use in templates with $ScaleWidth.
*
* @param int $width The width to set
* @return AssetContainer
*/
public function ScaleWidth($width)
{
$width = $this->castDimension($width, 'Width');
$variant = $this->variantName(__FUNCTION__, $width);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width) {
if ($backend->getWidth() === $width) {
return $this;
}
return $backend->resizeByWidth($width);
});
}
/**
* Proportionally scale down this image if it is wider than the specified width.
* Similar to ScaleWidth but without up-sampling. Use in templates with $ScaleMaxWidth.
*
* @uses ScalingManipulation::ScaleWidth()
* @param int $width The maximum width of the output image
* @return AssetContainer
*/
public function ScaleMaxWidth($width)
{
$width = $this->castDimension($width, 'Width');
$variant = $this->variantName(__FUNCTION__, $width);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width) {
if ($backend->getWidth() <= $width) {
return $this;
}
return $backend->resizeByWidth($width);
});
}
/**
* Scale image proportionally by height. Use in templates with $ScaleHeight.
*
* @param int $height The height to set
* @return AssetContainer
*/
public function ScaleHeight($height)
{
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($height) {
if ($backend->getHeight() === $height) {
return $this;
}
return $backend->resizeByHeight($height);
});
}
/**
* Proportionally scale down this image if it is taller than the specified height.
* Similar to ScaleHeight but without up-sampling. Use in templates with $ScaleMaxHeight.
*
* @uses ScalingManipulation::ScaleHeight()
* @param int $height The maximum height of the output image
* @return AssetContainer
*/
public function ScaleMaxHeight($height)
{
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($height) {
if ($backend->getHeight() <= $height) {
return $this;
}
return $backend->resizeByHeight($height);
});
}
/**
* Crop image on X axis if it exceeds specified width. Retain height.
* Use in templates with $CropWidth. Example: $Image.ScaleHeight(100).$CropWidth(100)
*
* @uses CropManipulation::Fill()
* @param int $width The maximum width of the output image
* @return AssetContainer
*/
public function CropWidth($width)
{
$variant = $this->variantName(__FUNCTION__, $width);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width) {
// Already within width
if ($backend->getWidth() <= $width) {
return $this;
}
// Crop to new width (same height)
return $backend->croppedResize($width, $backend->getHeight());
});
}
/**
* Crop image on Y axis if it exceeds specified height. Retain width.
* Use in templates with $CropHeight. Example: $Image.ScaleWidth(100).CropHeight(100)
*
* @uses CropManipulation::Fill()
* @param int $height The maximum height of the output image
* @return AssetContainer
*/
public function CropHeight($height)
{
$variant = $this->variantName(__FUNCTION__, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($height) {
// Already within height
if ($backend->getHeight() <= $height) {
return $this;
}
// Crop to new height (same width)
return $backend->croppedResize($backend->getWidth(), $height);
});
}
/**
* Crop this image to the aspect ratio defined by the specified width and height,
* then scale down the image to those dimensions if it exceeds them.
* Similar to Fill but without up-sampling. Use in templates with $FillMax.
*
* @uses self::Fill()
* @param int $width The relative (used to determine aspect ratio) and maximum width of the output image
* @param int $height The relative (used to determine aspect ratio) and maximum height of the output image
* @return AssetContainer
*/
public function FillMax($width, $height)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $width, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height) {
// Validate dimensions
$currentWidth = $backend->getWidth();
$currentHeight = $backend->getHeight();
if (!$currentWidth || !$currentHeight) {
return null;
}
if ($currentWidth === $width && $currentHeight === $height) {
return $this;
}
// Compare current and destination aspect ratios
$imageRatio = $currentWidth / $currentHeight;
$cropRatio = $width / $height;
if ($cropRatio < $imageRatio && $currentHeight < $height) {
// Crop off sides
return $backend->croppedResize(round($currentHeight * $cropRatio), $currentHeight);
} elseif ($currentWidth < $width) {
// Crop off top/bottom
return $backend->croppedResize($currentWidth, round($currentWidth / $cropRatio));
} else {
// Crop on both
return $backend->croppedResize($width, $height);
}
});
}
/**
* Resize and crop image to fill specified dimensions.
* Use in templates with $Fill
*
* @param int $width Width to crop to
* @param int $height Height to crop to
* @return AssetContainer
*/
public function Fill($width, $height)
{
$width = $this->castDimension($width, 'Width');
$height = $this->castDimension($height, 'Height');
$variant = $this->variantName(__FUNCTION__, $width, $height);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height) {
if ($backend->getWidth() === $width && $backend->getHeight() === $height) {
return $this;
}
return $backend->croppedResize($width, $height);
});
}
/**
* Set the quality of the resampled image
*
* @param int $quality Quality level from 0 - 100
* @return AssetContainer
* @throws InvalidArgumentException
*/
public function Quality($quality)
{
$quality = $this->castDimension($quality, 'Quality');
$variant = $this->variantName(__FUNCTION__, $quality);
return $this->manipulateImage($variant, function (Image_Backend $backend) use ($quality) {
return $backend->setQuality($quality);
});
}
/**
* Default CMS thumbnail
*
* @return DBFile|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon
*/
public function CMSThumbnail()
{
$width = (int)Config::inst()->get(__CLASS__, 'cms_thumbnail_width');
$height = (int)Config::inst()->get(__CLASS__, 'cms_thumbnail_height');
return $this->ThumbnailIcon($width, $height);
}
/**
* Generates a thumbnail for use in the gridfield view
*
* @return AssetContainer|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon
*/
public function StripThumbnail()
{
$width = (int)Config::inst()->get(__CLASS__, 'strip_thumbnail_width');
$height = (int)Config::inst()->get(__CLASS__, 'strip_thumbnail_height');
return $this->ThumbnailIcon($width, $height);
}
/**
* Get preview for this file
*
* @return AssetContainer|DBHTMLText Either a resized thumbnail, or html for a thumbnail icon
*/
public function PreviewThumbnail()
{
$width = (int)Config::inst()->get(__CLASS__, 'asset_preview_width');
return $this->ScaleMaxWidth($width) ?: $this->IconTag();
}
/**
* Default thumbnail generation for Images
*
* @param int $width
* @param int $height
* @return AssetContainer
*/
public function Thumbnail($width, $height)
{
return $this->Fill($width, $height);
}
/**
* Thubnail generation for all file types.
*
* Resizes images, but returns an icon `<img />` tag if this is not a resizable image
*
* @param int $width
* @param int $height
* @return AssetContainer|DBHTMLText
*/
public function ThumbnailIcon($width, $height)
{
return $this->Thumbnail($width, $height) ?: $this->IconTag();
}
/**
* Get HTML for img containing the icon for this file
*
* @return DBHTMLText
*/
public function IconTag()
{
/** @var DBHTMLText $image */
$image = DBField::create_field(
'HTMLFragment',
HTML::createTag('img', ['src' => $this->getIcon()])
);
return $image;
}
/**
* Get URL to thumbnail of the given size.
*
* May fallback to default icon
*
* @param int $width
* @param int $height
* @return string
*/
public function ThumbnailURL($width, $height)
{
$thumbnail = $this->Thumbnail($width, $height);
if ($thumbnail) {
return $thumbnail->getURL(false);
}
return $this->getIcon();
}
/**
* Convert the file to another format if there's a registered converter that can handle it.
*
* @param string $toExtension The file extension you want to convert to - e.g. "webp".
* @throws FileConverterException If the conversion fails and $returnNullOnFailure is false.
*/
public function Convert(string $toExtension): ?AssetContainer
{
// Verify this manipulation is applicable to this instance
if (!$this->exists()) {
return null;
}
$converter = Injector::inst()->get(FileConverterManager::class);
try {
return $converter->convert($this, $toExtension);
} catch (FileConverterException $e) {
/** @var LoggerInterface $logger */
$logger = Injector::inst()->get(LoggerInterface::class);
$logger->error($e->getMessage());
return null;
}
}
/**
* Return the relative URL of an icon for the file type,
* based on the {@link appCategory()} value.
* Images are searched for in "framework/images/app_icons/".
*
* @return string URL to icon
*/
public function getIcon()
{
$filename = $this->getFilename();
$ext = pathinfo($filename ?? '', PATHINFO_EXTENSION);
return File::get_icon_for_extension($ext);
}
/**
* Get Image_Backend instance for this image
*
* @return Image_Backend
*/
public function getImageBackend()
{
// Re-use existing image backend if set
if ($this->imageBackend) {
return $this->imageBackend;
}
// Skip files we know won't be an image
if (!$this->getIsImage() || !$this->getHash()) {
return null;
}
// Pass to backend service factory
try {
return $this->imageBackend = Injector::inst()->createWithArgs(Image_Backend::class, [$this]);
} catch (InjectorNotFoundException $ex) {
// Handle file-not-found errors
return null;
}
}
/**
* @param Image_Backend $backend
* @return $this
*/
public function setImageBackend(Image_Backend $backend)
{
$this->imageBackend = $backend;
return $this;
}
/**
* Get the width of this image.
*
* @return int
*/
public function getWidth()
{
$backend = $this->getImageBackend();
if ($backend) {
return $backend->getWidth();
}
return 0;
}
/**
* Get the height of this image.
*
* @return int
*/
public function getHeight()
{
$backend = $this->getImageBackend();
if ($backend) {
return $backend->getHeight();
}
return 0;
}
/**
* Get the orientation of this image.
*
* @return int ORIENTATION_SQUARE | ORIENTATION_PORTRAIT | ORIENTATION_LANDSCAPE
*/
public function getOrientation()
{
$width = $this->getWidth();
$height = $this->getHeight();
if ($width > $height) {
return Image_Backend::ORIENTATION_LANDSCAPE;
} elseif ($height > $width) {
return Image_Backend::ORIENTATION_PORTRAIT;
} else {
return Image_Backend::ORIENTATION_SQUARE;
}
}
/**
* Determine if this image is of the specified size
*
* @param int $width Width to check
* @param int $height Height to check
* @return boolean
*/
public function isSize($width, $height)
{
return $this->isWidth($width) && $this->isHeight($height);
}
/**
* Determine if this image is of the specified width
*
* @param int $width Width to check
* @return boolean
*/
public function isWidth($width)
{
$width = $this->castDimension($width, 'Width');
return $this->getWidth() === $width;
}
/**
* Determine if this image is of the specified width
*
* @param int $height Height to check
* @return boolean
*/
public function isHeight($height)
{
$height = $this->castDimension($height, 'Height');
return $this->getHeight() === $height;
}
/**
* Wrapper for manipulate() that creates a variant file with a different extension than the original file.
*
* @return DBFile|null The manipulated file
*/
public function manipulateExtension(string $newExtension, callable $callback)
{
$pathParts = pathinfo($this->getFilename());
$variant = $this->variantName(AbstractFileIDHelper::EXTENSION_REWRITE_VARIANT, $pathParts['extension'], $newExtension);
return $this->manipulate($variant, $callback);
}
/**
* Wrapper for manipulate that passes in and stores Image_Backend objects instead of tuples
*
* @param string $variant
* @param callable $callback Callback which takes an Image_Backend object, and returns an Image_Backend result.
* If this callback returns `true` then the current image will be duplicated without modification.
* @return DBFile|null The manipulated file
*/
public function manipulateImage($variant, $callback)
{
return $this->manipulate(
$variant,
function (AssetStore $store, $filename, $hash, $variant) use ($callback) {
$backend = $this->getImageBackend();
// If backend isn't available
if (!$backend || !$backend->getImageResource()) {
return null;
}
// Delegate to user manipulation
$result = $callback($backend);
// Empty result means no image generated
if (!$result) {
return null;
}
// Write from another container
if ($result instanceof AssetContainer) {
try {
$tuple = $store->setFromStream($result->getStream(), $filename, $hash, $variant);
return [$tuple, $result];
} finally {
// Unload the Intervention Image resource so it can be garbaged collected
$res = $backend->setImageResource(null);
gc_collect_cycles();
}
}
// Write from modified backend
if ($result instanceof Image_Backend) {
try {
$tuple = $result->writeToStore(
$store,
$filename,
$hash,
$variant,
['conflict' => AssetStore::CONFLICT_USE_EXISTING]
);
return [$tuple, $result];
} finally {
// Unload the Intervention Image resource so it can be garbaged collected
$res = $backend->setImageResource(null);
gc_collect_cycles();
}
}
// Unknown result from callback
throw new LogicException("Invalid manipulation result");
}
);
}
/**
* Generate a new DBFile instance using the given callback if it hasn't been created yet, or
* return the existing one if it has.
*
* @param string $variant name of the variant to create
* @param callable $callback Callback which should return a new tuple as an array.
* This callback will be passed the backend, filename, hash, and variant
* This will not be called if the file does not
* need to be created.
* @return DBFile|null The manipulated file
*/
public function manipulate($variant, $callback)
{
// Verify this manipulation is applicable to this instance
if (!$this->exists()) {
return null;
}
// Build output tuple
$filename = $this->getFilename();
$hash = $this->getHash();
$existingVariant = $this->getVariant();
if ($existingVariant) {
$variant = $existingVariant . '_' . $variant;
}
// Skip empty files (e.g. Folder does not have a hash)
if (empty($filename) || empty($hash)) {
return null;
}
// Create this asset in the store if it doesn't already exist,
// otherwise use the existing variant
$store = Injector::inst()->get(AssetStore::class);
$tuple = $manipulationResult = null;
if (!$store->exists($filename, $hash, $variant)) {
// Circumvent generation of thumbnails if we only want to get existing ones
if (!$this->getAllowGeneration()) {
return null;
}
$result = call_user_func($callback, $store, $filename, $hash, $variant);
// Preserve backward compatibility
list($tuple, $manipulationResult) = $result;
} else {
$tuple = [
'Filename' => $filename,
'Hash' => $hash,
'Variant' => $variant
];
}
// Callback may fail to perform this manipulation (e.g. resize on text file)