This repository has been archived by the owner on Sep 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageThumb.php
362 lines (315 loc) · 11.8 KB
/
ImageThumb.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
<?php
namespace TonchikTm\Yii2Thumb;
use Exception;
use Imagine\Exception\RuntimeException;
use Imagine\Image\Box;
use Imagine\Image\ImageInterface;
use Imagine\Image\ManipulatorInterface;
use Imagine\Image\Point;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\helpers\Html;
use yii\httpclient\Client as HttpClient;
use yii\imagine\Image;
/**
* Class ImageThumb
* @package TonchikTm\Yii2Thumb
*/
class ImageThumb
{
const THUMBNAIL_OUTBOUND = ManipulatorInterface::THUMBNAIL_OUTBOUND;
const THUMBNAIL_INSET = ManipulatorInterface::THUMBNAIL_INSET;
const THUMBNAIL_INSET_BOX = 'inset_box';
const THUMBNAIL_CROP = 'crop_box';
const QUALITY = 60;
const MKDIR_MODE = 0755;
const CHECK_REM_MODE_NONE = 1;
const CHECK_REM_MODE_CRC = 2;
const CHECK_REM_MODE_HEADER = 3;
/** @var string $cacheAlias path alias relative with @web where the cache files are kept */
public static $cacheAlias = 'assets/thumbnails';
/** @var int $cacheExpire */
public static $cacheExpire = 0;
/** @var yii\httpclient\Client */
public static $httpClient;
/**
*
* @param string $filename the image file path or path alias or URL
* @param integer $width the width in pixels to create the thumbnail
* @param integer $height the height in pixels to create the thumbnail
* @param array $options
* @return ImageInterface
* @throws FileNotFoundException
* @throws InvalidConfigException
*/
public static function thumbnail($filename, $width, $height, $options=[])
{
return Image::getImagine()
->open(static::thumbFile($filename, $width, $height, $options));
}
/**
*
* @param string $filename the image file path or path alias or URL
* @param integer $width the width in pixels to create the thumbnail
* @param integer $height the height in pixels to create the thumbnail
* @param array $options
* @return string
* @throws FileNotFoundException
* @throws InvalidConfigException
*/
public static function thumbFile($filename, $width, $height, $options=[])
{
$o = array_merge([
'format' => null, // format finally file
'mode' => self::THUMBNAIL_OUTBOUND, // mode of resizing original image to use in case both width and height specified
'quality' => null,
'crop' => null,
'cacheMode' => self::CHECK_REM_MODE_NONE, // check file version on remote server
], $options);
$fileContent = null;
$fileNameIsUrl = false;
if (\preg_match('/^https?:\/\//', $filename)) {
$fileNameIsUrl = true;
$commonCacheData = $filename . $width . $height . $o['mode'];
if (!empty($o['crop']['coord'])) $commonCacheData .= implode('', $o['crop']['coord']);
switch ($o['cacheMode']) {
case self::CHECK_REM_MODE_NONE:
$thumbnailFileName = \md5($commonCacheData);
break;
case self::CHECK_REM_MODE_CRC:
$fileContent = static::fileFromUrlContent($filename);
$thumbnailFileName = \md5($commonCacheData . \crc32($fileContent));
break;
case self::CHECK_REM_MODE_HEADER:
$fileContent = static::fileFromUrlContent($filename);
$thumbnailFileName = \md5($commonCacheData . static::fileFromUrlDate($filename));
break;
default:
throw new InvalidConfigException('Unknown `cacheMode` param value.');
}
} else {
$filename = FileHelper::normalizePath(Yii::getAlias($filename));
if (!\is_file($filename)) {
throw new FileNotFoundException("File {$filename} doesn't exist");
}
$commonCacheData = $filename . $width . $height . $o['mode'];
if (!empty($o['crop']['coord'])) $commonCacheData .= implode('', $o['crop']['coord']);
$thumbnailFileName = \md5($commonCacheData . \filemtime($filename));
}
$cachePath = Yii::getAlias('@webroot/' . static::$cacheAlias);
$thumbFileExt = $o['format'] ? '.' . $o['format'] : \strrchr($filename, '.');
$thumbFilePath = $cachePath . DIRECTORY_SEPARATOR . \substr($thumbnailFileName, 0, 2);
$thumbFile = $thumbFilePath . DIRECTORY_SEPARATOR . $thumbnailFileName . $thumbFileExt;
if (\file_exists($thumbFile)) {
if (static::$cacheExpire !== 0 && (\time() - \filemtime($thumbFile)) > static::$cacheExpire) {
\unlink($thumbFile);
} else {
return $thumbFile;
}
}
if (!\is_dir($thumbFilePath)) {
\mkdir($thumbFilePath, self::MKDIR_MODE, true);
}
if ($fileNameIsUrl) {
$image = Image::getImagine()->load($fileContent ?: static::fileFromUrlContent($filename));
} else {
$image = Image::getImagine()->open($filename);
}
if ($o['mode'] === self::THUMBNAIL_INSET_BOX) {
$image = $image->thumbnail(new Box($width, $height), ManipulatorInterface::THUMBNAIL_INSET);
} elseif ($o['mode'] === self::THUMBNAIL_CROP) {
$s = $o['crop'];
if (!empty($s['source'])) {
$ratio = $s['ratio'] ?? 1;
$image = $image->resize(new Box($s['source'][0]*$ratio, $s['source'][1]*$ratio));
}
$image = $image->crop(new Point($s['coord']['x']*$ratio, $s['coord']['y']*$ratio), new Box($s['coord']['w']*$ratio, $s['coord']['h']*$ratio));
$image->thumbnail(new Box($width, $height), ManipulatorInterface::THUMBNAIL_INSET);
} else {
$image = Image::thumbnail($image, $width, $height, $o['mode']);
}
$oSave = [
'quality' => $o['quality'] === null ? self::QUALITY : $o['quality']
];
$image->save($thumbFile, $oSave);
return $thumbFile;
}
/**
*
* @param string $filename the image file path or path alias or URL
* @param integer $width the width in pixels to create the thumbnail
* @param integer $height the height in pixels to create the thumbnail
* @param array $options
* @return string
* @throws FileNotFoundException
* @throws InvalidConfigException
*/
public static function thumbFileUrl($filename, $width, $height, $options=[])
{
$cacheUrl = Yii::getAlias('@web/' . static::$cacheAlias);
$thumbFilePath = static::thumbFile($filename, $width, $height, $options);
\preg_match('#[^\\' . DIRECTORY_SEPARATOR . ']+$#', $thumbFilePath, $matches);
$fileName = $matches[0];
return $cacheUrl . '/' . \substr($fileName, 0, 2) . '/' . $fileName;
}
/**
*
* @param string $filename the image file path or path alias or URL
* @param integer $width the width in pixels to create the thumbnail
* @param integer $height the height in pixels to create the thumbnail
* @param array $options
* @return string
*/
public static function thumbImg($filename, $width, $height, $options=[])
{
try {
$thumbFileUrl = static::thumbFileUrl($filename, $width, $height, $options);
} catch (Exception $e) {
return static::errorHandler($e, $filename);
}
$imgOptions = !empty($options['attributes']) ? $options['attributes'] : [];
return Html::img($thumbFileUrl, $imgOptions);
}
/**
*
* @param string $filename
* @param integer $width
* @param integer $height
* @param array $options
* @return string
*/
public static function thumbSource($filename, $width, $height, $options=[])
{
try {
$thumbFileUrl = static::thumbFileUrl($filename, $width, $height, $options);
} catch (Exception $e) {
return static::errorHandler($e, $filename);
}
$sourceOptions = [
'srcset' => $thumbFileUrl,
'type' => self::getMimeType($options['format'] ?: 'webp'),
];
return Html::tag('source', null, $sourceOptions);
}
/**
*
* @param string $filename
* @param integer $width
* @param integer $height
* @param array $options
* @return string
*/
public static function thumbPicture($filename, $width, $height, $options = [])
{
$oSource = !empty($options['source']) ? $options['source'] : [];
$oImg = !empty($options['img']) ? $options['img'] : [];
$pictureOptions = [ 'data-cache' => 'hit' ];
$sourceOptions = array_merge([
'format' => 'webp',
'mode' => self::THUMBNAIL_OUTBOUND,
'quality' => null,
'cacheMode' => self::CHECK_REM_MODE_NONE,
], $oSource);
return
Html::beginTag('picture', $pictureOptions) . "\n\t" .
self::thumbSource($filename, $width, $height, $sourceOptions) . "\n\t" .
self::thumbImg($filename, $width, $height, $oImg) . "\n" .
Html::endTag('picture');
}
/**
* Clear cache directory.
*
* @return bool
* @throws ErrorException
*/
public static function clearCache()
{
$cacheDir = Yii::getAlias('@webroot/' . static::$cacheAlias);
FileHelper::removeDirectory($cacheDir);
return @\mkdir($cacheDir, self::MKDIR_MODE, true);
}
/**
*
* @param Exception $error
* @param string $filename
* @return string
*/
protected static function errorHandler($error, $filename)
{
if ($error instanceof FileNotFoundException) {
return $error->getMessage();
}
Yii::warning("{$error->getCode()}\n{$error->getMessage()}\n{$error->getFile()}");
return 'Error ' . $error->getCode();
}
/**
*
* @param string $url
* @return string
* @throws FileNotFoundException
*/
protected static function fileFromUrlDate($url)
{
$response = self::getHttpClient()
->head($url)
->send();
if (!$response->isOk) {
throw new FileNotFoundException("URL {$url} doesn't exist");
}
return $response->headers['Last-Modified'];
}
/**
*
* @param string $url
* @return string
* @throws FileNotFoundException
*/
protected static function fileFromUrlContent($url)
{
$response = self::getHttpClient()
->createRequest()
->setMethod('GET')
->setUrl($url)
->send();
if (!$response->isOk) {
throw new FileNotFoundException("URL {$url} doesn't exist");
}
return $response->content;
}
/**
* @return HttpClient
*/
protected static function getHttpClient()
{
if (self::$httpClient === null || !(self::$httpClient instanceof HttpClient)) {
self::$httpClient = new HttpClient();
}
return self::$httpClient;
}
/**
* Get the mime type based on format.
*
* @param string $format
* @throws RuntimeException
* @return string mime-type
*/
private static function getMimeType($format)
{
static $mimeTypes = array(
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'wbmp' => 'image/vnd.wap.wbmp',
'xbm' => 'image/xbm',
'webp' => 'image/webp',
'bmp' => 'image/bmp',
);
if (!isset($mimeTypes[$format])) {
throw new RuntimeException(sprintf('Unsupported format given. Only %s are supported, %s given', implode(', ', array_keys($mimeTypes)), $format));
}
return $mimeTypes[$format];
}
}