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

@ -10,6 +10,7 @@ use App\Repository\WishRepository;
use App\Service\PlzToCoordinate; use App\Service\PlzToCoordinate;
use App\Service\DistanceCalculator; use App\Service\DistanceCalculator;
use App\Service\PhotoResizer;
use App\Service\OfferPhotoHelper; use App\Service\OfferPhotoHelper;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -24,9 +25,10 @@ class OfferController extends AbstractController
{ {
private $entityManager; private $entityManager;
public function __construct(EntityManagerInterface $entityManager) public function __construct(EntityManagerInterface $entityManager, PhotoResizer $photoresizer)
{ {
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
$this->photoresizer = $photoresizer;
} }
#[Route('/offers', name: 'offers')] #[Route('/offers', name: 'offers')]
@ -62,6 +64,8 @@ class OfferController extends AbstractController
$this->entityManager->persist($offer); $this->entityManager->persist($offer);
$this->entityManager->flush(); $this->entityManager->flush();
$this->photoresizer->resize($photoDir.'/'.$offer->getPhotoFilename());
$this->addFlash("success", "Successfully added the new offer!"); $this->addFlash("success", "Successfully added the new offer!");
return $this->redirectToRoute('offers'); return $this->redirectToRoute('offers');
} }

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);
}
}