From 72418dd5a4130b67133020b0e8c062650c59916f Mon Sep 17 00:00:00 2001 From: thisfro Date: Wed, 12 Jan 2022 17:51:45 +0100 Subject: [PATCH] Resize image after upload using imagine --- src/Controller/OfferController.php | 6 ++++- src/Service/PhotoResizer.php | 37 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/Service/PhotoResizer.php diff --git a/src/Controller/OfferController.php b/src/Controller/OfferController.php index d6f51c6..9425e3b 100644 --- a/src/Controller/OfferController.php +++ b/src/Controller/OfferController.php @@ -10,6 +10,7 @@ use App\Repository\WishRepository; use App\Service\PlzToCoordinate; use App\Service\DistanceCalculator; +use App\Service\PhotoResizer; use App\Service\OfferPhotoHelper; use Doctrine\ORM\EntityManagerInterface; @@ -24,9 +25,10 @@ class OfferController extends AbstractController { private $entityManager; - public function __construct(EntityManagerInterface $entityManager) + public function __construct(EntityManagerInterface $entityManager, PhotoResizer $photoresizer) { $this->entityManager = $entityManager; + $this->photoresizer = $photoresizer; } #[Route('/offers', name: 'offers')] @@ -62,6 +64,8 @@ class OfferController extends AbstractController $this->entityManager->persist($offer); $this->entityManager->flush(); + $this->photoresizer->resize($photoDir.'/'.$offer->getPhotoFilename()); + $this->addFlash("success", "Successfully added the new offer!"); return $this->redirectToRoute('offers'); } diff --git a/src/Service/PhotoResizer.php b/src/Service/PhotoResizer.php new file mode 100644 index 0000000..65c7b90 --- /dev/null +++ b/src/Service/PhotoResizer.php @@ -0,0 +1,37 @@ +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); + } +} \ No newline at end of file