| 1 |
<?php |
| 2 |
|
| 3 |
namespace League\Glide\Manipulators; |
| 4 |
|
| 5 |
use Intervention\Image\Image; |
| 6 |
|
| 7 |
/** |
| 8 |
* @property string $fm |
| 9 |
* @property string $q |
| 10 |
*/ |
| 11 |
class Encode extends BaseManipulator |
| 12 |
{ |
| 13 |
/** |
| 14 |
* Perform output image manipulation. |
| 15 |
* |
| 16 |
* @param Image $image The source image. |
| 17 |
* |
| 18 |
* @return Image The manipulated image. |
| 19 |
*/ |
| 20 |
public function run(Image $image) |
| 21 |
{ |
| 22 |
$format = $this->getFormat($image); |
| 23 |
$quality = $this->getQuality(); |
| 24 |
|
| 25 |
if (in_array($format, ['jpg', 'pjpg'], true)) { |
| 26 |
$image = $image->getDriver() |
| 27 |
->newImage($image->width(), $image->height(), '#fff') |
| 28 |
->insert($image, 'top-left', 0, 0); |
| 29 |
} |
| 30 |
|
| 31 |
if ('pjpg' === $format) { |
| 32 |
$image->interlace(); |
| 33 |
$format = 'jpg'; |
| 34 |
} |
| 35 |
|
| 36 |
return $image->encode($format, $quality); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Resolve format. |
| 41 |
* |
| 42 |
* @param Image $image The source image. |
| 43 |
* |
| 44 |
* @return string The resolved format. |
| 45 |
*/ |
| 46 |
public function getFormat(Image $image) |
| 47 |
{ |
| 48 |
if (array_key_exists($this->fm, static::supportedFormats())) { |
| 49 |
return $this->fm; |
| 50 |
} |
| 51 |
|
| 52 |
return array_search($image->mime(), static::supportedFormats(), true) ?: 'jpg'; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Get a list of supported image formats and MIME types. |
| 57 |
* |
| 58 |
* @return array<string,string> |
| 59 |
*/ |
| 60 |
public static function supportedFormats() |
| 61 |
{ |
| 62 |
return [ |
| 63 |
'avif' => 'image/avif', |
| 64 |
'gif' => 'image/gif', |
| 65 |
'jpg' => 'image/jpeg', |
| 66 |
'pjpg' => 'image/jpeg', |
| 67 |
'png' => 'image/png', |
| 68 |
'webp' => 'image/webp', |
| 69 |
'tiff' => 'image/tiff', |
| 70 |
]; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Resolve quality. |
| 75 |
* |
| 76 |
* @return int The resolved quality. |
| 77 |
*/ |
| 78 |
public function getQuality() |
| 79 |
{ |
| 80 |
$default = 90; |
| 81 |
|
| 82 |
if (!is_numeric($this->q)) { |
| 83 |
return $default; |
| 84 |
} |
| 85 |
|
| 86 |
if ($this->q < 0 or $this->q > 100) { |
| 87 |
return $default; |
| 88 |
} |
| 89 |
|
| 90 |
return (int) $this->q; |
| 91 |
} |
| 92 |
} |
| 93 |
|