-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathEncode.php
92 lines (79 loc) · 2.03 KB
/
Encode.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
<?php
namespace League\Glide\Manipulators;
use Intervention\Image\Image;
/**
* @property string $fm
* @property string $q
*/
class Encode extends BaseManipulator
{
/**
* Perform output image manipulation.
*
* @param Image $image The source image.
*
* @return Image The manipulated image.
*/
public function run(Image $image)
{
$format = $this->getFormat($image);
$quality = $this->getQuality();
if (in_array($format, ['jpg', 'pjpg'], true)) {
$image = $image->getDriver()
->newImage($image->width(), $image->height(), '#fff')
->insert($image, 'top-left', 0, 0);
}
if ('pjpg' === $format) {
$image->interlace();
$format = 'jpg';
}
return $image->encode($format, $quality);
}
/**
* Resolve format.
*
* @param Image $image The source image.
*
* @return string The resolved format.
*/
public function getFormat(Image $image)
{
if (array_key_exists($this->fm, static::supportedFormats())) {
return $this->fm;
}
return array_search($image->mime(), static::supportedFormats(), true) ?: 'jpg';
}
/**
* Get a list of supported image formats and MIME types.
*
* @return array<string,string>
*/
public static function supportedFormats()
{
return [
'avif' => 'image/avif',
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'pjpg' => 'image/jpeg',
'png' => 'image/png',
'webp' => 'image/webp',
'tiff' => 'image/tiff',
];
}
/**
* Resolve quality.
*
* @return int The resolved quality.
*/
public function getQuality()
{
$default = 90;
if (!is_numeric($this->q)) {
return $default;
}
if ($this->q < 0 or $this->q > 100) {
return $default;
}
return (int) $this->q;
}
}