|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace BWC\Share\Image; |
|
4
|
|
|
|
|
5
|
|
|
class ImageResizer extends ImageManipulator |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* @var resource |
|
9
|
|
|
*/ |
|
10
|
|
|
private $_image; |
|
11
|
|
|
|
|
12
|
|
|
public function fromString($image) |
|
13
|
|
|
{ |
|
14
|
|
|
$this->_image = imagecreatefromstring($image); |
|
15
|
|
|
imagealphablending($this->_image, false); |
|
16
|
|
|
imagesavealpha($this->_image, true); |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
|
|
public function toString($format = self::FORMAT_PNG, $quality = null) |
|
20
|
|
|
{ |
|
21
|
|
|
return $this->formatImageData($this->_image, $format, $quality); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function scaleToFit($width, $height, $force = false) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->scale($width, $height, true, $force); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function scaleToCover($width, $height, $force = false) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->scale($width, $height, false, $force); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param int $width Target width |
|
36
|
|
|
* @param int $height Target height |
|
37
|
|
|
* @param bool $toFit If true, image fill fit to given dimensions, if false, it will cover them |
|
38
|
|
|
* @param bool $force If true, image will be resized even if target dimensions are larger than original |
|
39
|
|
|
*/ |
|
40
|
|
|
protected function scale($width, $height, $toFit, $force) |
|
41
|
|
|
{ |
|
42
|
|
|
if (null === $this->_image) return; |
|
43
|
|
|
|
|
44
|
|
|
$rawWidth = $this->_getWidth(); |
|
45
|
|
|
$rawHeight = $this->_getHeight(); |
|
46
|
|
|
|
|
47
|
|
|
$widthOver = $rawWidth / $width; |
|
48
|
|
|
$heightOver = $rawHeight / $height; |
|
49
|
|
|
|
|
50
|
|
|
if ($toFit) { |
|
51
|
|
|
$scalingFactor = max($widthOver, $heightOver); |
|
52
|
|
|
} else { |
|
53
|
|
|
$scalingFactor = min($widthOver, $heightOver); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if ($scalingFactor > 1 || $force) { |
|
57
|
|
|
$destWidth = $rawWidth / $scalingFactor; |
|
58
|
|
|
$destHeight = $rawHeight / $scalingFactor; |
|
59
|
|
|
|
|
60
|
|
|
$destImage = imagecreatetruecolor($destWidth, $destHeight); |
|
61
|
|
|
imagealphablending($destImage, false); |
|
62
|
|
|
imagesavealpha($destImage, true); |
|
63
|
|
|
$transparent = imagecolorallocatealpha($destImage, 255, 255, 255, 127); |
|
64
|
|
|
imagefill($destImage, 0, 0, $transparent); |
|
65
|
|
|
|
|
66
|
|
|
imagecopyresampled($destImage, $this->_image, 0, 0, 0, 0, $destWidth, $destHeight, $rawWidth, $rawHeight); |
|
67
|
|
|
|
|
68
|
|
|
$this->_image = $destImage; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
protected function _getWidth() |
|
73
|
|
|
{ |
|
74
|
|
|
return $this->_image ? imagesx($this->_image) : null; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
protected function _getHeight() |
|
78
|
|
|
{ |
|
79
|
|
|
return $this->_image ? imagesy($this->_image) : null; |
|
80
|
|
|
} |
|
81
|
|
|
} |