Resize image after upload using imagine

This commit is contained in:
Jannis Portmann 2022-01-12 17:51:45 +01:00
parent 27474ad2ea
commit 72418dd5a4
2 changed files with 42 additions and 1 deletions

View file

@ -0,0 +1,37 @@
<?php
// Source: https://symfony.com/doc/current/the-fast-track/en/23-imagine.html
namespace App\Service;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
class PhotoResizer
{
private const MAX_WIDTH = 1000;
private const MAX_HEIGHT = 1000;
private $imagine;
public function __construct()
{
$this->imagine = new Imagine();
}
public function resize(string $filename): void
{
list($iwidth, $iheight) = getimagesize($filename);
$ratio = $iwidth / $iheight;
$width = self::MAX_WIDTH;
$height = self::MAX_HEIGHT;
if ($width / $height > $ratio) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}
$photo = $this->imagine->open($filename);
$photo->resize(new Box($width, $height))->save($filename);
}
}