/
ImageSizerEngineIMagickCLI.module
344 lines (304 loc) · 11.7 KB
/
ImageSizerEngineIMagickCLI.module
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
<?php namespace ProcessWire;
/**
* ImageSizer Engine ImageMagick
*
* Copyright (C) 2016 by Horst Nogajski
*
* @property string $imageMagickPath Module configuration value
*
*/
class ImageSizerEngineIMagickCLI extends ImageSizerEngine implements Module, ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => 'ImageSizerEngine ImageMagick CLI',
'version' => 11,
'summary' => "Upgrades image manipulations to use The CLI (exec) version of ImageMagick",
'author' => 'Horst Nogajski',
'autoload' => false,
'singular' => false,
'requires' => array('ProcessWire>=3.0.10')
);
}
/**
* @var bool|null
*
*/
static protected $supported = null;
/**
* @var string
*
*/
protected $IMPATH;
/**
* @var ?
*
*/
protected $imageDepth;
/**
* @var ?
*
*/
protected $imageFormat;
/**
* Construct
*
*/
public function __construct() {
// the logfile will be used in debug mode only
$this->log = new FileLog(wire('config')->paths->logs . 'imagesizerengine-imagick-cli.txt');
// set a lower default quality of 80, which is more like 90 in GD
$this->setQuality(80);
$this->set('imageMagickPath', '');
parent::__construct();
}
/**
* Get shell path
*
* @param string $path
* @return string mixed
*
*/
protected static function shellpath($path, $isDir = true) {
if('/' != DIRECTORY_SEPARATOR) {
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
}
$path = rtrim($path, DIRECTORY_SEPARATOR) . ($isDir ? DIRECTORY_SEPARATOR : '');
return $path;
}
/**
* Get valid source image formats
*
* @return array
*
*/
protected function validSourceImageFormats() {
return array('PNG', 'JPG', 'JPEG', 'GIF');
}
/**
* Is this module supported for resizeing images
*
* @param string $action
* @return bool|null
*
*/
public function supported($action = '') {
if(self::$supported !== null) return self::$supported;
$config = $this->wire('config');
$debug = $config->debug || $action == 'install';
// config.imageMagickPath overrides module configured imageMagickPath
if($config->imageMagickPath) $this->imageMagickPath = $config->imageMagickPath;
if(!$this->IMPATH) {
if(!$this->imageMagickPath) {
self::$supported = false;
return false;
}
$this->IMPATH = self::shellpath($this->imageMagickPath);
}
// for regular (production runtime) checks, we skip the remaining checks,
// but when installing the module, we do a full check
if('install' != $action) return true;
// full check:
$s = ini_get('disable_functions');
if($s) {
$a = explode(',', str_replace(' ', '', mb_strtolower($s)));
if(in_array('exec', $a)) {
if($debug) $this->warning(sprintf($this->_("%s - The PHP exec() function is not allowed!"), __CLASS__));
self::$supported = false;
return false;
}
}
$executable = 'convert';
if(!is_executable($this->IMPATH . $executable) && !is_executable($this->IMPATH . $executable . '.exe')) {
if($debug) $this->warning(sprintf($this->_("%s - Missing executable: %s"), __CLASS__, $executable));
self::$supported = false;
return false;
}
self::$supported = true;
return true;
}
/**
* Process the image resize
*
* @param string $srcFilename Source file
* @param string $dstFilename Destination file
* @param int $fullWidth Current width
* @param int $fullHeight Current height
* @param int $finalWidth Requested final width
* @param int $finalHeight Requested final height
* @return bool
* @throws WireException
*
*/
protected function processResize($srcFilename, $dstFilename, $fullWidth, $fullHeight, $finalWidth, $finalHeight) {
$this->setTimeLimit(120);
$srcFilename = self::shellpath($srcFilename, false);
$dstFilename = self::shellpath($dstFilename, false);
@unlink($dstFilename);
@clearstatcache(dirname($dstFilename));
$this->modified = false;
$this->imageDepth = $this->info['bits'];
$this->imageFormat = strtoupper(str_replace('image/', '', $this->info['mime']));
if(!in_array($this->imageFormat, $this->validSourceImageFormats())) {
throw new WireException(sprintf($this->_("loaded file '%s' is not in the list of valid images", basename($dstFilename))));
}
$tickets = array();
$orientations = null;
$needRotation = $this->autoRotation !== true ? false : ($this->checkOrientation($orientations) && (!empty($orientations[0]) || !empty($orientations[1])) ? true : false);
if($this->rotate || $needRotation) {
$degrees = $this->rotate ? $this->rotate : ((is_float($orientations[0]) || is_int($orientations[0])) && $orientations[0] > -361 && $orientations[0] < 361 ? $orientations[0] : false);
if($degrees !== false && !in_array($degrees, array(-360, 0, 360))) {
$tickets[0][] = '-background transparent -rotate ' . (float) $degrees;
if(abs($degrees) == 90 || abs($degrees) == 270) {
// we have to swap width & height now!
$this->setImageInfo($fullHeight, $fullWidth);
}
}
}
if($this->flip || $needRotation) {
$vertical = null;
if($this->flip) {
$vertical = $this->flip == 'v';
} else if($orientations[1] > 0) {
$vertical = $orientations[1] == 2;
}
if(!is_null($vertical)) $tickets[0][] = $vertical ? '-flip' : '-flop';
}
if(is_array($this->cropExtra) && 4 == count($this->cropExtra)) { // crop before resize
list($cropX, $cropY, $cropWidth, $cropHeight) = $this->cropExtra;
$tickets[1][] = sprintf('-crop %dx%d+%d+%d!', $cropWidth, $cropHeight, $cropX, $cropY);
$this->setImageInfo($cropWidth, $cropHeight);
}
$bgX = $bgY = 0;
$bgWidth = $fullWidth;
$bgHeight = $fullHeight;
$resizemethod = $this->getResizeMethod($bgWidth, $bgHeight, $finalWidth, $finalHeight, $bgX, $bgY);
if(0 == $resizemethod) {
$this->sharpening = 'none'; // no need for sharpening because we use original copy without scaling
$this->setImageInfo($fullWidth, $fullHeight);
}
if(2 == $resizemethod) { // 2 = resize with aspect ratio
$tickets[2][] = sprintf('-resize %dx%d!', $finalWidth, $finalHeight);
$this->setImageInfo($finalWidth, $finalHeight);
}
if(4 == $resizemethod) { // 4 = resize and crop from center with aspect ratio
$tickets[2][] = sprintf('-resize %dx%d!', $bgWidth, $bgHeight);
$tickets[2][] = sprintf('-crop %dx%d+%d+%d!', $finalWidth, $finalHeight, $bgX, $bgY);
$this->setImageInfo($finalWidth, $finalHeight);
}
if($this->sharpening && $this->sharpening != 'none') {
$a = $this->imSharpen($this->sharpening);
$tickets[2][] = sprintf('-unsharp %sx%s+%s+%s', $a[0], $a[1], $a[2], $a[3]);
}
// EXECUTE ALL AT ONCE
$out = array();
$ret = 0;
if(!isset($tickets[0])) $tickets[0] = array();
if(!isset($tickets[2])) $tickets[2] = array();
if(isset($tickets[1]) && 0 < count($tickets[1])) {
$ticket = implode(' ', $tickets[0]) . ' ' . implode(' ', $tickets[1]) . ' | "' .
$this->IMPATH . 'convert" ' . implode(' ', $tickets[2]);
} else {
$ticket = implode(' ', $tickets[0]) . ' ' . implode(' ', $tickets[2]);
}
// added 16bit workspace and optionally gamma correction
$gammaLinearized = $gammaRestored = '';
if($this->defaultGamma && $this->defaultGamma != -1) {
$gammaLinearized = '-gamma 0.454545';
$gammaRestored = '-gamma 2.2';
}
$cmd = null;
if(\IMAGETYPE_JPEG == $this->imageType) {
$cmd =
"\"{$this->IMPATH}convert\" \"$srcFilename\" -depth 16 $gammaLinearized -filter lanczos {$ticket} $gammaRestored " .
"-depth 8 -quality {$this->quality} -sampling-factor 1x1 -strip \"$dstFilename\"";
} else if(\IMAGETYPE_PNG == $this->imageType) {
$cmd =
"\"{$this->IMPATH}convert\" \"$srcFilename\" -depth 16 $gammaLinearized {$ticket} $gammaRestored " .
"-depth 8 -strip \"$dstFilename\"";
} else if(\IMAGETYPE_GIF == $this->imageType) {
$cmd =
"\"{$this->IMPATH}convert\" \"$srcFilename\" -depth 16 $gammaLinearized {$ticket} $gammaRestored " .
"-depth 8 -strip \"$dstFilename\"";
}
if(is_null($cmd)) {
return false;
} else {
@exec($cmd, $out, $ret);
}
if(0 != $ret) return false; // uhm, something went wrong
return true;
}
/**
* Return array of info for performing a sharpen
*
* @param string $mode
* @return array
*
*/
protected function imSharpen($mode) {
$mp = intval($this->finalHeight * $this->finalWidth);
if($mp > 1440000) {
switch($mode) {
case 'strong':
$m = array(0, 0.5, 4.6, 0.03);
break;
case 'medium':
$m = array(0, 0.5, 3.0, 0.04);
break;
case 'soft':
default:
$m = array(0, 0.5, 2.3, 0.07);
break;
}
} else if($mp > 480000) {
switch($mode) {
case 'strong':
$m = array(0, 0.5, 3.0, 0.04);
break;
case 'medium':
$m = array(0, 0.5, 2.3, 0.06);
break;
case 'soft':
default:
$m = array(0, 0.5, 1.8, 0.08);
break;
}
} else {
// we have small variations, thumbnails
switch($mode) {
case 'strong':
$m = array(0, 0.5, 2.0, 0.06);
break;
case 'medium':
$m = array(0, 0.5, 1.7, 0.08);
break;
case 'soft':
default:
$m = array(0, 0.5, 1.2, 0.1);
break;
}
}
return $m;
}
/**
* Configure module
*
* @param InputfieldWrapper $inputfields
*
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields) {
parent::getModuleConfigInputfields($inputfields);
if($this->wire('config')->imageMagickPath) {
$this->imageMagickPath = $this->wire('config')->imageMagickPath;
$this->message('Image magick path is defined in /site/config.php: $config->imageMagickPath');
} else {
$f = $this->wire('modules')->get('InputfieldText');
$f->attr('name', 'imageMagickPath');
$f->label = $this->_('Server path to ImageMagick CLI executables');
$f->attr('value', $this->imageMagickPath);
$inputfields->add($f);
}
// report warnings if there are potential issues using ImageMagick CLI
if($this->imageMagickPath) $this->supported('install');
}
}