Passed
Push — master ( 317cbb...5e97e8 )
by smiley
02:43
created

Imagetiler::setOptimizer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * Class Imagetiler
4
 *
5
 * @filesource   Imagetiler.php
6
 * @created      20.06.2018
7
 * @package      chillerlan\Imagetiler
8
 * @author       smiley <[email protected]>
9
 * @copyright    2018 smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\Imagetiler;
14
15
use chillerlan\Traits\ContainerInterface;
16
use ImageOptimizer\Optimizer;
17
use Imagick;
18
use Psr\Log\{LoggerAwareInterface, LoggerAwareTrait, LoggerInterface, NullLogger};
19
20
class Imagetiler implements LoggerAwareInterface{
21
	use LoggerAwareTrait;
22
23
	/**
24
	 * @var \chillerlan\Imagetiler\ImagetilerOptions
25
	 */
26
	protected $options;
27
28
	/**
29
	 * @var \ImageOptimizer\Optimizer
30
	 */
31
	protected $optimizer;
32
33
	/**
34
	 * Imagetiler constructor.
35
	 *
36
	 * @param \chillerlan\Traits\ContainerInterface|null $options
37
	 * @param \ImageOptimizer\Optimizer                  $optimizer
38
	 * @param \Psr\Log\LoggerInterface|null              $logger
39
	 *
40
	 * @throws \chillerlan\Imagetiler\ImagetilerException
41
	 */
42
	public function __construct(ContainerInterface $options = null, Optimizer $optimizer = null, LoggerInterface $logger = null){
43
44
		if(!extension_loaded('imagick')){
45
			throw new ImagetilerException('Imagick extension is not available');
46
		}
47
48
		$this->setOptions($options ?? new ImagetilerOptions);
49
		$this->setLogger($logger ?? new NullLogger);
50
51
		if($optimizer instanceof Optimizer){
52
			$this->setOptimizer($optimizer);
53
		}
54
	}
55
56
	/**
57
	 * @param \chillerlan\Traits\ContainerInterface $options
58
	 *
59
	 * @return \chillerlan\Imagetiler\Imagetiler
60
	 * @throws \chillerlan\Imagetiler\ImagetilerException
61
	 */
62
	public function setOptions(ContainerInterface $options):Imagetiler{
63
		$options->zoom_min = max(0, $options->zoom_min);
64
		$options->zoom_max = max(1, $options->zoom_max);
65
66
		if($options->zoom_normalize === null || $options->zoom_max < $options->zoom_normalize){
67
			$options->zoom_normalize = $options->zoom_max;
68
		}
69
70
		if($options->tile_ext === null){
71
			$options->tile_ext = $this->getExtension($options->tile_format);
72
		}
73
74
		$this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type chillerlan\Traits\ContainerInterface, but the property $options was declared to be of type chillerlan\Imagetiler\ImagetilerOptions. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
75
76
		if(ini_set('memory_limit', $this->options->memory_limit) === false){
77
			throw new ImagetilerException('could not alter ini settings');
78
		}
79
80
		if(ini_get('memory_limit') !== (string)$this->options->memory_limit){
81
			throw new ImagetilerException('ini settings differ from options');
82
		}
83
84
		if($this->options->imagick_tmp !== null && is_dir($this->options->imagick_tmp)){
85
			apache_setenv('MAGICK_TEMPORARY_PATH', $this->options->imagick_tmp);
86
			putenv('MAGICK_TEMPORARY_PATH='.$this->options->imagick_tmp);
87
		}
88
89
90
		return $this;
91
	}
92
93
	/**
94
	 * @param \ImageOptimizer\Optimizer $optimizer
95
	 *
96
	 * @return \chillerlan\Imagetiler\Imagetiler
97
	 */
98
	public function setOptimizer(Optimizer $optimizer):Imagetiler{
99
		$this->optimizer = $optimizer;
100
101
		return $this;
102
	}
103
104
	/**
105
	 * @param string $image_path
106
	 * @param string $out_path
107
	 *
108
	 * @return \chillerlan\Imagetiler\Imagetiler
109
	 * @throws \chillerlan\Imagetiler\ImagetilerException
110
	 */
111
	public function process(string $image_path, string $out_path):Imagetiler{
112
113
		if(!is_file($image_path) || !is_readable($image_path)){
114
			throw new ImagetilerException('cannot read image '.$image_path);
115
		}
116
117
		if(!is_dir($out_path)|| !is_writable($out_path)){
118
119
			if(!mkdir($out_path, 0755, true)){
120
				throw new ImagetilerException('output path is not writable');
121
			}
122
123
		}
124
125
		// prepare the zoom base images
126
		$this->prepareZoomBaseImages($image_path, $out_path);
127
128
		// create the tiles
129
		for($zoom = $this->options->zoom_min; $zoom <= $this->options->zoom_max; $zoom++){
130
131
			$base_image = $out_path.'/'.$zoom.'.'.$this->options->tile_ext;
132
133
			//load image
134
			if(!is_file($base_image) || !is_readable($base_image)){
135
				throw new ImagetilerException('cannot read base image '.$base_image.' for zoom '.$zoom);
136
			}
137
138
			$this->createTilesForZoom(new Imagick($base_image), $zoom, $out_path);
139
		}
140
141
		// clean up base images
142
		if($this->options->clean_up){
143
144
			for($zoom = $this->options->zoom_min; $zoom <= $this->options->zoom_max; $zoom++){
145
				$lvl_file = $out_path.'/'.$zoom.'.'.$this->options->tile_ext;
146
147
				if(is_file($lvl_file)){
148
					if(unlink($lvl_file)){
149
						$this->logger->info('deleted base image for zoom level '.$zoom.': '.$lvl_file);
150
					}
151
				}
152
			}
153
154
		}
155
156
		return $this;
157
	}
158
159
	/**
160
	 * prepare base images for each zoom level
161
	 *
162
	 * @param string $image_path
163
	 * @param string $out_path
164
	 */
165
	protected function prepareZoomBaseImages(string $image_path, string $out_path):void{
166
		$im = new Imagick($image_path);
167
		$im->setImageFormat($this->options->tile_format);
168
169
		$width  = $im->getimagewidth();
170
		$height = $im->getImageHeight();
171
172
		$this->logger->info('input image loaded: ['.$width.'x'.$height.'] '.$image_path);
173
174
		$start = true;
175
		$il    = null;
176
177
		for($zoom = $this->options->zoom_max; $zoom >= $this->options->zoom_min; $zoom--){
178
			$base_image = $out_path.'/'.$zoom.'.'.$this->options->tile_ext;
179
180
			// check if the base image already exists
181
			if(!$this->options->overwrite_base_image && is_file($base_image)){
182
				$this->logger->info('base image for zoom level '.$zoom.' already exists: '.$base_image);
183
				continue;
184
			}
185
186
			[$w, $h] = $this->getSize($width, $height, $zoom);
187
188
			// fit main image to current zoom level
189
			$il = $start ? clone $im : $il;
190
191
			$this->options->fast_resize === true
192
				// scaleImage - works fast, but without any quality configuration
193
				? $il->scaleImage($w, $h, true)
0 ignored issues
show
Bug introduced by
The method scaleImage() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

193
				? $il->/** @scrutinizer ignore-call */ scaleImage($w, $h, true)

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
194
				// resizeImage - works slower but offers better quality
195
				: $il->resizeImage($w, $h, $this->options->resize_filter, $this->options->resize_blur);
196
197
			$this->saveImage($il, $base_image);
0 ignored issues
show
Bug introduced by
It seems like $il can also be of type null; however, parameter $image of chillerlan\Imagetiler\Imagetiler::saveImage() does only seem to accept Imagick, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

197
			$this->saveImage(/** @scrutinizer ignore-type */ $il, $base_image);
Loading history...
198
199
			if($start){
200
				$this->clearImage($im);
201
			}
202
203
			$start = false;
204
			$this->logger->info('created image for zoom level '.$zoom.' ['.$w.'x'.$h.'] '.$base_image);
205
		}
206
207
		$this->clearImage($il);
208
	}
209
210
	/**
211
	 * create tiles for each zoom level
212
	 *
213
	 * @param \Imagick                       $im
214
	 * @param int                            $zoom
215
	 * @param string                         $out_path
216
	 * @param \ImageOptimizer\Optimizer|null $optimizer
217
	 *
218
	 * @return void
219
	 */
220
	protected function createTilesForZoom(Imagick $im, int $zoom, string $out_path, Optimizer $optimizer = null):void{
221
		$w = $im->getimagewidth();
222
		$h = $im->getImageHeight();
223
224
		$ts = $this->options->tile_size;
225
226
		$x = (int)ceil($w / $ts);
227
		$y = (int)ceil($h / $ts);
228
229
		// width
230
		for($ix = 0; $ix < $x; $ix++){
231
			$cx = $ix * $ts;
232
233
			// create a stripe tile_size * height
234
			$ci = clone $im;
235
			$ci->cropImage($ts, $h, $cx, 0);
236
237
			// height
238
			for($iy = 0; $iy < $y; $iy++){
239
				$tile = $out_path.'/'.sprintf($this->options->store_structure, $zoom, $ix, $iy).'.'.$this->options->tile_ext;
240
241
				// check if tile already exists
242
				if(!$this->options->overwrite_tile_image && is_file($tile)){
243
					$this->logger->info('tile '.$zoom.'/'.$x.'/'.$y.' already exists: '.$tile);
244
245
					continue;
246
				}
247
248
				// cut the stripe into pieces of height = tile_size
249
				$cy = $this->options->tms
250
					? $h - ($iy + 1) * $ts
251
					: $iy * $ts;
252
253
				$ti = clone $ci;
254
				$ti->setImagePage(0, 0, 0, 0);
255
				$ti->cropImage($ts, $ts, 0, $cy);
256
257
				// check if the current tile is smaller than the tile size (leftover edges on the input image)
258
				if($ti->getImageWidth() < $ts || $ti->getimageheight() < $ts){
259
260
					$th = $this->options->tms
261
						? $im->getImageHeight() - $ts
262
						: 0;
263
264
					$ti->setImageBackgroundColor($this->options->fill_color);
265
					$ti->extentImage($ts, $ts, 0, $th);
266
				}
267
268
				$this->saveImage($ti, $tile, $optimizer);
0 ignored issues
show
Unused Code introduced by
The call to chillerlan\Imagetiler\Imagetiler::saveImage() has too many arguments starting with $optimizer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

268
				$this->/** @scrutinizer ignore-call */ 
269
           saveImage($ti, $tile, $optimizer);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
269
				$this->clearImage($ti);
270
			}
271
272
			$this->clearImage($ci);
273
			$this->logger->info('created column '.($ix+1).', x = '.$cx);
274
		}
275
276
		$this->clearImage($im);
277
		$this->logger->info('created tiles for zoom level: '.$zoom.', '.$y.' tile(s) per column');
278
	}
279
280
	/**
281
	 * save image in to destination
282
	 *
283
	 * @param Imagick                   $image
284
	 * @param string                    $dest full path with file name
285
	 *
286
	 * @return void
287
	 * @throws \chillerlan\Imagetiler\ImagetilerException
288
	 */
289
	protected function saveImage(Imagick $image, string $dest):void{
290
		$dir = dirname($dest);
291
292
		if(!is_dir($dir)){
293
			if(!mkdir($dir, 0755, true)){
294
				throw new ImagetilerException('cannot crate folder '.$dir);
295
			}
296
		}
297
298
		if($this->options->tile_format === 'jpeg'){
299
			$image->setCompression(Imagick::COMPRESSION_JPEG);
300
			$image->setCompressionQuality($this->options->quality_jpeg);
301
		}
302
303
		if(!$image->writeImage($dest)){
304
			throw new ImagetilerException('cannot save image '.$dest);
305
		}
306
307
		if($this->options->optimize_output && $this->optimizer instanceof Optimizer){
308
			$this->optimizer->optimize($dest);
309
		}
310
311
	}
312
313
	/**
314
	 * free resources, destroy imagick object
315
	 *
316
	 * @param \Imagick|null $image
317
	 *
318
	 * @return bool
319
	 */
320
	protected function clearImage(Imagick $image = null):bool{
321
322
		if($image instanceof Imagick){
323
			$image->clear();
324
325
			return $image->destroy();
326
		}
327
328
		return false;
329
	}
330
331
	/**
332
	 * calculate the image size for the given zoom level
333
	 *
334
	 * @param int $width
335
	 * @param int $height
336
	 * @param int $zoom
337
	 *
338
	 * @return int[]
339
	 */
340
	protected function getSize(int $width, int $height, int $zoom):array{
341
342
		if($this->options->zoom_max > $this->options->zoom_normalize && $zoom > $this->options->zoom_normalize){
343
			$zd = 2 ** ($zoom - $this->options->zoom_normalize);
344
345
			return [$zd * $width, $zd * $height];
346
		}
347
348
		if($zoom < $this->options->zoom_normalize){
349
			$zd = 2 ** ($this->options->zoom_normalize - $zoom);
350
351
			return [(int)round($width / $zd), (int)round($height / $zd)];
352
		}
353
354
		return [$width, $height];
355
	}
356
357
	/**
358
	 * return file extension depend of given format
359
	 *
360
	 * @param string $format
361
	 *
362
	 * @return string
363
	 * @throws \chillerlan\Imagetiler\ImagetilerException
364
	 */
365
	protected function getExtension(string $format):string{
366
367
		if(in_array($format, ['jpeg', 'jp2', 'jpc', 'jxr',], true)){
368
			return 'jpg';
369
		}
370
371
		if(in_array($format, ['png', 'png00', 'png8', 'png24', 'png32', 'png64',], true)){
372
			return 'png';
373
		}
374
375
		throw new ImagetilerException('invalid file format');
376
	}
377
378
}
379