2020-04-27 20:32:24 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2024-07-11 15:09:08 +00:00
|
|
|
use Illuminate\Support\Arr;
|
2020-04-27 20:32:24 +00:00
|
|
|
use Intervention\Image\Constraint;
|
|
|
|
use Intervention\Image\ImageManager;
|
|
|
|
|
|
|
|
class ImageWriter
|
|
|
|
{
|
2020-06-12 13:55:45 +00:00
|
|
|
private const DEFAULT_MAX_WIDTH = 500;
|
|
|
|
private const DEFAULT_QUALITY = 80;
|
2020-04-27 20:32:24 +00:00
|
|
|
|
2024-07-11 15:09:08 +00:00
|
|
|
private string $supportedFormat = 'jpg';
|
|
|
|
|
2024-04-18 14:36:28 +00:00
|
|
|
public function __construct(private readonly ImageManager $imageManager)
|
2020-04-27 20:32:24 +00:00
|
|
|
{
|
2024-07-11 15:21:25 +00:00
|
|
|
$this->supportedFormat = self::getSupportedFormat();
|
2024-07-11 15:09:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private static function getSupportedFormat(): string
|
|
|
|
{
|
|
|
|
return Arr::get(gd_info(), 'WebP Support') ? 'webp' : 'jpg';
|
2020-04-27 20:32:24 +00:00
|
|
|
}
|
|
|
|
|
2022-07-16 22:42:29 +00:00
|
|
|
public function write(string $destination, object|string $source, array $config = []): void
|
2020-04-27 20:32:24 +00:00
|
|
|
{
|
2020-06-12 15:05:18 +00:00
|
|
|
$img = $this->imageManager
|
2022-07-16 22:42:29 +00:00
|
|
|
->make($source)
|
2020-06-12 13:55:45 +00:00
|
|
|
->resize(
|
|
|
|
$config['max_width'] ?? self::DEFAULT_MAX_WIDTH,
|
2020-12-22 20:11:22 +00:00
|
|
|
null,
|
|
|
|
static function (Constraint $constraint): void {
|
2020-06-12 13:55:45 +00:00
|
|
|
$constraint->upsize();
|
|
|
|
$constraint->aspectRatio();
|
|
|
|
}
|
2020-06-12 15:05:18 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
if (isset($config['blur'])) {
|
|
|
|
$img->blur($config['blur']);
|
|
|
|
}
|
|
|
|
|
2024-07-11 15:09:08 +00:00
|
|
|
$img->save($destination, $config['quality'] ?? self::DEFAULT_QUALITY, $this->supportedFormat);
|
2020-04-27 20:32:24 +00:00
|
|
|
}
|
|
|
|
}
|