Completed
Push — master ( 327ddb...5776a0 )
by Daniel
17:43
created

ImagickBackend::resizeRatio()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 5
nop 3
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 15 and the first side effect is on line 12.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
use SilverStripe\Filesystem\Storage\AssetContainer;
4
use SilverStripe\Filesystem\Storage\AssetStore;
5
6
/**
7
 * @package framework
8
 * @subpackage filesystem
9
 */
10
11
if(!class_exists('Imagick')) {
12
	return;
13
}
14
15
class ImagickBackend extends Imagick implements Image_Backend {
16
17
	/**
18
	 * @config
19
	 * @var int
20
	 */
21
	private static $default_quality = 75;
22
23
	/**
24
	 * Create a new backend with the given object
25
	 *
26
	 * @param AssetContainer $assetContainer Object to load from
27
	 */
28
	public function __construct(AssetContainer $assetContainer = null) {
29
		parent::__construct();
30
31
		if($assetContainer) {
32
			$this->loadFromContainer($assetContainer);
33
		}
34
	}
35
36
	public function loadFromContainer(AssetContainer $assetContainer) {
37
		$stream = $assetContainer->getStream();
38
		$this->readimagefile($stream);
39
		fclose($stream);
40
		$this->setDefaultQuality();
41
	}
42
43
	public function loadFrom($path) {
44
		$this->readimage($path);
45
		$this->setDefaultQuality();
46
	}
47
48
	protected function setDefaultQuality() {
49
		$this->setQuality(Config::inst()->get('ImagickBackend', 'default_quality'));
50
	}
51
52
	public function writeToStore(AssetStore $assetStore, $filename, $hash = null, $variant = null, $config = array()) {
53
		// Write to temporary file, taking care to maintain the extension
54
		$path = tempnam(sys_get_temp_dir(), 'imagemagick');
55
		if($extension = pathinfo($filename, PATHINFO_EXTENSION)) {
56
			$path .= "." . $extension;
57
		}
58
		$this->writeimage($path);
59
		$result = $assetStore->setFromLocalFile($path, $filename, $hash, $variant, $config);
60
		unlink($path);
61
		return $result;
62
	}
63
64
	public function writeTo($path) {
65
		Filesystem::makeFolder(dirname($path));
66
		if(is_dir(dirname($path))) {
67
			$this->writeImage($path);
68
		}
69
	}
70
71
	public function setQuality($quality) {
72
		$this->setImageCompressionQuality($quality);
73
	}
74
75
	public function resize($width, $height) {
76
		if(!$this->valid()) {
77
			return null;
78
		}
79
80
		if($width < 0 || $height < 0) {
81
			throw new InvalidArgumentException("Image resizing dimensions cannot be negative");
82
		}
83
		if(!$width && !$height) {
84
			throw new InvalidArgumentException("No dimensions given when resizing image");
85
		}
86
		if(!$width) {
87
			throw new InvalidArgumentException("Width not given when resizing image");
88
		}
89
		if(!$height) {
90
			throw new InvalidArgumentException("Height not given when resizing image");
91
		}
92
93
		//use whole numbers, ensuring that size is at least 1x1
94
		$width = max(1, round($width));
95
		$height = max(1, round($height));
96
97
		$geometry = $this->getImageGeometry();
98
99
		// Check that a resize is actually necessary.
100
		if ($width === $geometry["width"] && $height === $geometry["height"]) {
101
			return $this;
102
		}
103
104
		$new = clone $this;
105
		$new->resizeImage($width, $height, self::FILTER_LANCZOS, 1);
106
107
		return $new;
108
	}
109
110
	public function resizeRatio($maxWidth, $maxHeight, $useAsMinimum = false) {
111
		if(!$this->valid()) {
112
			return null;
113
		}
114
115
		$geometry = $this->getImageGeometry();
116
117
		$widthRatio = $maxWidth / $geometry["width"];
118
		$heightRatio = $maxHeight / $geometry["height"];
119
120
		if( $widthRatio < $heightRatio ) {
121
			return $useAsMinimum
122
				? $this->resizeByHeight( $maxHeight )
123
				: $this->resizeByWidth( $maxWidth );
124
		} else {
125
			return $useAsMinimum
126
				? $this->resizeByWidth( $maxWidth )
127
				: $this->resizeByHeight( $maxHeight );
128
		}
129
	}
130
131
	public function resizeByWidth($width) {
132
		if(!$this->valid()) {
133
			return null;
134
		}
135
136
		$geometry = $this->getImageGeometry();
137
138
		$heightScale = $width / $geometry["width"];
139
		return $this->resize( $width, $heightScale * $geometry["height"] );
140
	}
141
142
	public function resizeByHeight($height) {
143
		if(!$this->valid()) {
144
			return null;
145
		}
146
147
		$geometry = $this->getImageGeometry();
148
149
		$scale = $height / $geometry["height"];
150
		return $this->resize( $scale * $geometry["width"], $height );
151
	}
152
153
	/**
154
	 * paddedResize
155
	 *
156
	 * @param int $width
157
	 * @param int $height
158
	 * @param int $transparencyPercent
159
	 * @return Image_Backend
160
	 */
161
	public function paddedResize($width, $height, $backgroundColor = "FFFFFF", $transparencyPercent = 0) {
162
		if(!$this->valid()) {
163
			return null;
164
		}
165
		
166
		//keep the % within bounds of 0-100
167
		$transparencyPercent = min(100, max(0, $transparencyPercent));
168
169
		$new = $this->resizeRatio($width, $height);
170
		if($transparencyPercent) {
171
			$alphaHex = $this->calculateAlphaHex($transparencyPercent);
172
			$new->setImageBackgroundColor("#{$backgroundColor}{$alphaHex}");
173
		} else {
174
			$new->setImageBackgroundColor("#{$backgroundColor}");
175
		}
176
		$w = $new->getImageWidth();
177
		$h = $new->getImageHeight();
178
		$new->extentImage($width,$height,($w-$width)/2,($h-$height)/2);
179
		return $new;
180
	}
181
182
	/**
183
	 * Convert a percentage (or 'true') to a two char hex code to signifiy the level of an alpha channel
184
	 *
185
	 * @param $percent
186
	 * @return string
187
	 */
188
	public function calculateAlphaHex($percent) {
189
		if($percent > 100) {
190
			$percent = 100;
191
		}
192
		// unlike GD, this uses 255 instead of 127, and is reversed. Lower = more transparent
193
		$alphaHex = dechex(255 - floor(255 * bcdiv($percent, 100, 2)));
194
		if(strlen($alphaHex) == 1) {
195
			$alphaHex =  '0' .$alphaHex;
196
		}
197
		return $alphaHex;
198
	}
199
200
201
	/**
202
	 * croppedResize
203
	 *
204
	 * @param int $width
205
	 * @param int $height
206
	 * @return Image_Backend
207
	 */
208
	public function croppedResize($width, $height) {
209
		if(!$this->valid()) {
210
			return null;
211
		}
212
213
		$width = round($width);
214
		$height = round($height);
215
		$geo = $this->getImageGeometry();
216
217
		// Check that a resize is actually necessary.
218
		if ($width == $geo["width"] && $height == $geo["height"]) {
219
			return $this;
220
		}
221
222
		$new = clone $this;
223
		$new->setBackgroundColor(new ImagickPixel('transparent'));
224
225
		if(($geo['width']/$width) < ($geo['height']/$height)){
226
			$new->cropImage(
227
				$geo['width'],
228
				floor($height*$geo['width']/$width),
229
				0,
230
				($geo['height'] - ($height*$geo['width']/$width))/2
231
			);
232
		}else{
233
			$new->cropImage(
234
				ceil($width*$geo['height']/$height),
235
				$geo['height'],
236
				($geo['width'] - ($width*$geo['height']/$height))/2,
237
				0
238
			);
239
		}
240
		$new->ThumbnailImage($width,$height,true);
241
		return $new;
242
	}
243
}
244