|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Liip\ImagineBundle\Imagine\Filter\Loader; |
|
4
|
|
|
|
|
5
|
|
|
use Imagine\Filter\Basic\Resize; |
|
6
|
|
|
use Imagine\Image\ImageInterface; |
|
7
|
|
|
use Imagine\Image\Box; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Scale filter. |
|
11
|
|
|
* |
|
12
|
|
|
* @author Devi Prasad <https://github.com/deviprsd21> |
|
13
|
|
|
*/ |
|
14
|
|
|
class ScaleFilterLoader implements LoaderInterface |
|
15
|
|
|
{ |
|
16
|
|
|
public function __construct($dimentionKey = 'dim', $ratioKey = 'to', $absoluteRatio = true) |
|
17
|
|
|
{ |
|
18
|
|
|
$this->dimentionKey = $dimentionKey; |
|
|
|
|
|
|
19
|
|
|
$this->ratioKey = $ratioKey; |
|
|
|
|
|
|
20
|
|
|
$this->absoluteRatio = $absoluteRatio; |
|
|
|
|
|
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* {@inheritdoc} |
|
25
|
|
|
*/ |
|
26
|
|
|
public function load(ImageInterface $image, array $options = array()) |
|
27
|
|
|
{ |
|
28
|
|
|
if (!isset($options[$this->dimentionKey]) && !isset($options[$this->ratioKey])) { |
|
29
|
|
|
throw new \InvalidArgumentException("Missing $this->dimentionKey or $this->ratioKey option."); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
$size = $image->getSize(); |
|
33
|
|
|
$origWidth = $size->getWidth(); |
|
34
|
|
|
$origHeight = $size->getHeight(); |
|
35
|
|
|
|
|
36
|
|
|
if (isset($options[$this->ratioKey])) { |
|
37
|
|
|
$ratio = $this->absoluteRatio ? $options[$this->ratioKey] : $this->calcAbsoluteRatio($options[$this->ratioKey]); |
|
38
|
|
|
} elseif (isset($options[$this->dimentionKey])) { |
|
39
|
|
|
list($width, $height) = $options[$this->dimentionKey]; |
|
40
|
|
|
|
|
41
|
|
|
$widthRatio = $width / $origWidth; |
|
42
|
|
|
$heightRatio = $height / $origHeight; |
|
43
|
|
|
|
|
44
|
|
|
if (null == $width || null == $height) { |
|
45
|
|
|
$ratio = max($widthRatio, $heightRatio); |
|
46
|
|
|
} else { |
|
47
|
|
|
$ratio = min($widthRatio, $heightRatio); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
if ($this->isImageProcessable($ratio)) { |
|
52
|
|
|
$filter = new Resize(new Box(round($origWidth * $ratio), round($origHeight * $ratio))); |
|
|
|
|
|
|
53
|
|
|
|
|
54
|
|
|
return $filter->apply($image); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $image; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
protected function calcAbsoluteRatio($ratio) |
|
61
|
|
|
{ |
|
62
|
|
|
return $ratio; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
protected function isImageProcessable($ratio) |
|
66
|
|
|
{ |
|
67
|
|
|
return true; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: