-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThumbnail.php
499 lines (412 loc) · 15.9 KB
/
Thumbnail.php
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<?php
namespace fabiomlferreira\filemanager;
use Yii;
use yii\helpers\Html;
use Imagine\Image\Box;
use yii\imagine\Image;
use yii\base\Exception;
use Imagine\Image\Point;
use yii\helpers\FileHelper;
use Kinglozzer\TinyPng\Compressor;
use Imagine\Image\ManipulatorInterface;
use fabiomlferreira\filemanager\assets\ThumbnailAsset;
/**
* Class Thumbnail
* @package fabiomlferreira\filemanager
*/
class Thumbnail extends \yii\base\Component
{
/**
* Path to cache directory
* @var string
*/
public $cachePath = '@runtime/thumbnails';
/**
* Base path
* @var null
*/
public $basePath = null;
/**
* Prefix path
* @var null
*/
public $prefixPath = null;
/**
* Image cache expire
* @var int
*/
public $cacheExpire = 604800;
/**
* Options
* @var array
*/
public $options = [];
private $tiny;
private $image;
private $defaultOptions = [
'placeholder' => [
'type' => Thumbnail::PLACEHOLDER_TYPE_URL,
'backgroundColor' => '#f5f5f5',
'textColor' => '#cdcdcd',
'textSize' => 30,
'text' => 'Ooops!',
'random' => false,
'cache' => true
],
'quality' => 92,
'tinyPng' => [
'apiKey' => null
]
];
const THUMBNAIL_OUTBOUND = ManipulatorInterface::THUMBNAIL_OUTBOUND;
const THUMBNAIL_INSET = ManipulatorInterface::THUMBNAIL_INSET;
const PLACEHOLDER_TYPE_JS = 'js';
const PLACEHOLDER_TYPE_URL = 'url';
const FUNCTION_CROP = 'crop';
const FUNCTION_RESIZE = 'resize';
const FUNCTION_THUMBNAIL = 'thumbnail';
const FUNCTION_WATERMARK = 'watermark';
const FUNCTION_COMPRESS = 'compress';
public function init()
{
if (isset($this->options['placeholder']) && count($this->options['placeholder'])) {
$this->options['placeholder'] = array_merge($this->defaultOptions['placeholder'], $this->options['placeholder']);
} else {
$this->options['placeholder'] = $this->defaultOptions['placeholder'];
}
$this->options['quality'] = (!isset($this->options['quality']) || !is_numeric($this->options['quality']))
? $this->defaultOptions['quality']
: $this->options['quality'];
if ($this->options['placeholder']['type'] == Thumbnail::PLACEHOLDER_TYPE_JS) {
ThumbnailAsset::register(Yii::$app->getView());
}
if (isset($this->options['tinyPng']) && count($this->options['tinyPng'])) {
$this->options['tinyPng'] = array_merge($this->defaultOptions['tinyPng'], $this->options['tinyPng']);
} else {
$this->options['tinyPng'] = $this->defaultOptions['tinyPng'];
}
if (!is_null($this->options['tinyPng']['apiKey'])) {
$this->tiny = new Compressor($this->options['tinyPng']['apiKey']);
}
}
/**
* Creates and caches the image thumbnail and returns <img> tag
* @param string $file
* @param array $params
* @param array $options
* @return string
*/
public function img($file, array $params, $options = [])
{
$cacheFileSrc = $this->make($file, $params);
if (!$cacheFileSrc) {
if (isset($params['placeholder'])) {
return $this->placeholder($params['placeholder'], $options);
} else {
return null;
}
}
return Html::img($cacheFileSrc, $options);
}
/**
* Creates and caches the image thumbnail and returns image url
* @param string $file
* @param array $params
* @return string
*/
public function url($file, array $params)
{
$cacheFileSrc = $this->make($file, $params);
return $cacheFileSrc ? $cacheFileSrc : null;
}
/**
* Image placeholder
* @param array $params
* @param array $options
* @return null|string
*/
public function placeholder(array $params, $options = [])
{
$placeholder = null;
$width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
$height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;
if (is_null($width) || is_null($height)) {
throw new Exception('Wrong placeholder width or height');
}
if (isset($params['backgroundColor']) && $this->checkHexColor($params['backgroundColor'])) {
$backgroundColor = $params['backgroundColor'];
} else {
$backgroundColor = $this->options['placeholder']['backgroundColor'];
}
if (isset($params['textColor']) && $this->checkHexColor($params['textColor'])) {
$textColor = $params['textColor'];
} else {
$textColor = $this->options['placeholder']['textColor'];
}
$textSize = (isset($params['textSize']) && is_numeric($params['textSize'])) ? $params['textSize'] : $this->options['placeholder']['textSize'];
$text = !empty($params['text']) ? $params['text'] : $this->options['placeholder']['text'];
$random = isset($params['random']) ? $params['random'] : $this->options['placeholder']['random'];
if ($this->options['placeholder']['type'] == self::PLACEHOLDER_TYPE_URL) {
$placeholder = $this->urlPlaceholder($width, $height, $text, $backgroundColor, $textColor, $textSize,
$random, $options);
} elseif ($this->options['placeholder']['type'] == self::PLACEHOLDER_TYPE_JS) {
$placeholder = $this->jsPlaceholder($width, $height, $text, $backgroundColor, $textColor, $random, $options);
}
return $placeholder;
}
/**
* Return URL placeholder image
* @param integer $width
* @param integer $height
* @param string $text
* @param string $backgroundColor
* @param string $textColor
* @param array $options
* @return string
*/
private function urlPlaceholder($width, $height, $text, $backgroundColor, $textColor, $textSize, $random, array
$options)
{
if ($random) {
$backgroundColor = $this->getRandomColor();
}
$src = 'https://placeholdit.imgix.net/~text?txtsize=' . $textSize . '&bg=' . str_replace('#', '',
$backgroundColor) . '&txtclr=' . str_replace('#', '', $textColor) . '&txt=' . $text . '&w=' . $width . '&h=' . $height;
if (!$this->options['placeholder']['cache']) {
return Html::img($src, $options);
}
$cacheFileName = md5($width . $height . $text . $backgroundColor . $textColor . $textSize);
$cacheFileExt = '.jpg';
$cacheFileDir = '/' . substr($cacheFileName, 0, 2);
$cacheFilePath = Yii::getAlias($this->cachePath) . $cacheFileDir;
$cacheFile = $cacheFilePath . '/' . $cacheFileName . $cacheFileExt;
$cacheUrl = str_replace('\\', '/', preg_replace('/^@[a-z]+/', '', $this->cachePath) . $cacheFileDir . '/'
. $cacheFileName . $cacheFileExt);
if (file_exists($cacheFile)) {
if ($this->cacheExpire !== 0 && (time() - filemtime($cacheFile)) > $this->cacheExpire) {
unlink($cacheFile);
} else {
return Html::img($cacheUrl, $options);
}
}
if (!is_dir($cacheFilePath)) {
mkdir($cacheFilePath, 0755, true);
}
$image = file_get_contents($src);
file_put_contents($cacheFile, $image);
return Html::img($cacheUrl, $options);
}
/**
* Return JS placeholder image
* @param integer $width
* @param integer $height
* @param string $text
* @param string $backgroundColor
* @param string $textColor
* @param array $options
* @return string
*/
private function jsPlaceholder($width, $height, $text, $backgroundColor, $textColor, $random, array $options)
{
$src = 'holder.js/' . $width . 'x' . $height . '?bg=' . $backgroundColor . '&fg=' . $textColor . '&text=' . $text;
if ($random) {
$src .= $src . '&random=yes';
}
return Html::img('', array_merge($options, ['data-src' => $src]));
}
/**
* Make image and save to cache
* @param string $filePath
* @param array $params
* @return string
*/
private function make($filePath, array $params)
{
if (!is_null($this->basePath)) {
$fileFullPath = FileHelper::normalizePath(Yii::getAlias($this->basePath . '/' . $filePath));
} else {
$fileFullPath = FileHelper::normalizePath($filePath);
}
$fileFullPath = urldecode($fileFullPath);
if (!is_file($fileFullPath)) {
return false;
}
$quality = isset($params['quality']) ? $params['quality'] : $this->options['quality'];
$cacheFileName = md5($fileFullPath . serialize($params) . $quality . filemtime($fileFullPath));
$cacheFileExt = strrchr($fileFullPath, '.');
$cacheFileDir = '/' . substr($cacheFileName, 0, 2);
$cacheFilePath = Yii::getAlias($this->cachePath) . $cacheFileDir;
$cacheFile = $cacheFilePath . '/' . $cacheFileName . $cacheFileExt;
$cacheUrl = str_replace('\\', '/', preg_replace('/^@[a-z]+/', '', $this->cachePath) . $cacheFileDir . '/'
. $cacheFileName . $cacheFileExt);
$cacheUrl = !is_null($this->prefixPath) ? $this->prefixPath . $cacheUrl : $cacheUrl;
if (file_exists($cacheFile)) {
if ($this->cacheExpire !== 0 && (time() - filemtime($cacheFile)) > $this->cacheExpire) {
unlink($cacheFile);
} else {
return $cacheUrl;
}
}
if (!is_dir($cacheFilePath)) {
mkdir($cacheFilePath, 0755, true);
}
try{
$this->image = Image::getImagine()->open($fileFullPath);
}catch(\Imagine\Exception\RuntimeException $e){
return null;
}catch(\Imagine\Exception\InvalidArgumentException $e){
return null;
}
foreach ($params as $key => $value) {
switch ($key) {
case self::FUNCTION_THUMBNAIL :
$this->thumbnail($value);
break;
case self::FUNCTION_RESIZE :
$this->resize($value);
break;
case self::FUNCTION_CROP :
$this->crop($value);
break;
case self::FUNCTION_WATERMARK :
$this->watermark($value);
break;
}
}
$this->image->save($cacheFile, [
'quality' => $quality
]);
if (array_key_exists(self::FUNCTION_COMPRESS, $params)) {
if ($params[self::FUNCTION_COMPRESS] && !is_null($this->options['tinyPng']['apiKey'])) {
$result = $this->tiny->compress($cacheFile);
$result->writeTo($cacheFile);
}
}
return $cacheUrl;
}
/**
* Get random color
* @return string
*/
private function getRandomColor()
{
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
/**
* Check hex color
* @param string $hex
* @return int
*/
private function checkHexColor($hex)
{
return preg_match('/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/', $hex);
}
/**
* Crop image
* @param array $params
*/
private function crop(array $params)
{
$x = (isset($params['x']) && is_numeric($params['x'])) ? $params['x'] : 0;
$y = (isset($params['y']) && is_numeric($params['y'])) ? $params['y'] : 0;
$width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
$height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;
if (is_null($width) || is_null($height)) {
throw new Exception('Wrong crop width or height');
}
$this->image->crop(new Point($x, $y), new Box($width, $height));
}
/**
* Resize image
* @param array $params
*/
private function resize(array $params)
{
$width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
$height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;
if (!is_null($width) && !is_null($height)) {
$this->image->resize(new Box($width, $height));
} elseif (!is_null($width)) {
$height = $this->image->getSize()->getHeight() / ($this->image->getSize()->getWidth() / $width);
$this->image->resize(new Box($width, $height));
} elseif (!is_null($height)) {
$width = $this->image->getSize()->getWidth() / ($this->image->getSize()->getHeight() / $height);
$this->image->resize(new Box($width, $height));
} else {
throw new Exception('Wrong resize width or height');
}
}
/**
* Make thumbnail image
* @param array $params
*/
private function thumbnail(array $params)
{
$mode = isset($params['mode']) ? $params['mode'] : self::THUMBNAIL_OUTBOUND;
$width = (isset($params['width']) && is_numeric($params['width'])) ? $params['width'] : null;
$height = (isset($params['height']) && is_numeric($params['height'])) ? $params['height'] : null;
if (is_null($width) || is_null($height)) {
throw new Exception('Wrong thumbnail width or height');
}
$this->image = $this->image->thumbnail(new Box($width, $height), $mode);
}
/**
* Add watermark to image
* @param array $params Set watermark params
* @throws Exception Bad params
*/
private function watermark(array $params)
{
if (isset($params['posX']) && is_numeric($params['posX'])) {
$posX = $params['posX'];
} else {
$posX = null;
}
if (isset($params['posY']) && is_numeric($params['posY'])) {
$posY = $params['posY'];
} else {
$posY = null;
}
if (is_null($posX) || is_null($posY)) {
throw new Exception('Wrong watermark coordinates');
}
if (isset($params['width']) && is_numeric($params['width'])) {
$width = $params['width'];
} else {
$width = 0;
}
if (isset($params['height']) && is_numeric($params['height'])) {
$height = $params['height'];
} else {
$height = 0;
}
$mode = isset($params['mode']) ? $params['mode'] : self::THUMBNAIL_OUTBOUND;
if (isset($params['image']) && file_exists(Yii::getAlias($params['image']))) {
$watermarkPath = Yii::getAlias($params['image']);
} else {
$watermarkPath = null;
}
if (is_null($watermarkPath)) {
throw new Exception('Incorrect watermark image path');
}
$watermark = Image::getImagine()->open($watermarkPath);
if ($this->image->getSize()->getHeight() < $posY + $watermark->getSize()->getHeight() ||
$this->image->getSize()->getWidth() < $posX + $watermark->getSize()->getWidth()
) {
throw new Exception('Cannot paste watermark of the given size at the specified position, as it moves outside of the image\'s box');
}
if ($width > 0 && $height > 0) {
$height = $this->image->getSize()->getHeight();
$width = $this->image->getSize()->getWidth();
$watermark = $watermark->thumbnail(new Box($width, $height), $mode);
}
if ($posX < 0) {
$posX = $this->image->getSize()->getWidth() - abs($posX) - $watermark->getSize()->getWidth();
}
if ($posY < 0) {
$posY = $this->image->getSize()->getHeight() - abs($posY) - $watermark->getSize()->getHeight();
}
$position = new Point($posX, $posY);
$this->image->paste($watermark, $position);
}
}