55 lines
1.3 KiB
PHP
55 lines
1.3 KiB
PHP
|
<?php
|
||
|
declare(strict_types=1);
|
||
|
|
||
|
|
||
|
namespace ImageResizer\Lib;
|
||
|
|
||
|
use ImageResizer\Models\ResizeParams;
|
||
|
use ImageResizer\Models\Image;
|
||
|
class Resizer
|
||
|
{
|
||
|
public function __construct(
|
||
|
private readonly ImageDb $imageDb
|
||
|
)
|
||
|
{}
|
||
|
|
||
|
/**
|
||
|
* @throws \Exception
|
||
|
*/
|
||
|
public function performResize(string $path, ResizeParams $params)
|
||
|
{
|
||
|
// Check if the image has already been processed
|
||
|
if ($image = $this->imageDb->findImage($path, $params)) {
|
||
|
|
||
|
header("Content-type: {${$image->getMime()}}");
|
||
|
return base64_decode($image->encode(75));
|
||
|
}
|
||
|
|
||
|
// Fetch the image at the given URL
|
||
|
$original_img = Image::fromUrl($_ENV['root_domain'] . $path);
|
||
|
$converted = $this->createVariant($original_img, $params);
|
||
|
|
||
|
// Store the image in the database
|
||
|
$this->imageDb->saveImage(
|
||
|
$path,
|
||
|
$params,
|
||
|
$converted
|
||
|
);
|
||
|
|
||
|
header("Content-type: {$original_img->getMime()}");
|
||
|
return base64_decode($converted);
|
||
|
}
|
||
|
|
||
|
private function createVariant(Image $original, ResizeParams $params): string
|
||
|
{
|
||
|
$quality = $params->quality ?: -1;
|
||
|
|
||
|
if ($params->width) {
|
||
|
$original->toWidth($params->width);
|
||
|
}
|
||
|
|
||
|
return $original->encode($quality);
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|