2023-08-25 19:50:52 +00:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
|
|
namespace ImageResizer\Lib;
|
|
|
|
|
|
|
|
use ImageResizer\Models\ResizeParams;
|
|
|
|
use ImageResizer\Models\Image;
|
|
|
|
class Resizer
|
|
|
|
{
|
|
|
|
public function __construct(
|
2023-08-26 18:10:53 +00:00
|
|
|
private readonly ImageDb $imageDb
|
2023-08-25 19:50:52 +00:00
|
|
|
)
|
|
|
|
{}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @throws \Exception
|
|
|
|
*/
|
|
|
|
public function performResize(string $path, ResizeParams $params)
|
|
|
|
{
|
|
|
|
// Check if the image has already been processed
|
|
|
|
if ($image = $this->imageDb->findImage($path, $params)) {
|
2023-08-26 18:10:53 +00:00
|
|
|
|
2023-08-25 19:50:52 +00:00
|
|
|
header("Content-type: {${$image->getMime()}}");
|
|
|
|
return base64_decode($image->encode(75));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch the image at the given URL
|
2023-08-25 20:24:51 +00:00
|
|
|
$original_img = Image::fromUrl($_ENV['ROOT_DOMAIN'] . $path);
|
2023-08-25 19:50:52 +00:00
|
|
|
$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;
|
|
|
|
|
2023-08-25 20:24:51 +00:00
|
|
|
$original->toWidth($params->width ?? intval($_ENV["DEFAULT_WIDTH"]));
|
2023-08-25 19:50:52 +00:00
|
|
|
|
|
|
|
return $original->encode($quality);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|