Reputation: 51
I am trying to figure out how to resize an image on upload with symfony 5. Actually my fileupload is working perfectly, but it would be such a relief not to resize all my pics before I have to upload them.
Is there a way I can do this?
Here is my upload code:
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
#CAN'T RESIZE HERE BEFORE UPLOAD ???
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
#.....persist - flush etc.
}
Upvotes: 2
Views: 3985
Reputation: 51
First this is my controller with a method to upload an image from a form:
/**
* @Route("/admin/image/new", name="admin_image_new")
*/
public function newImage(Request $request, EntityManagerInterface $manager, FileUploader $fileUploader, ImageResizeService $imageResize)
{
$image = new Image();
$form = $this->createForm(ImageType::class, $image);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$imageFile = $form->get('file')->getData();
if($imageFile) {
$imageFileName = $fileUploader->upload($imageFile);
$image->setFilename($imageFileName);
}
$manager->persist($image);
$manager->flush();
$this->addFlash('success', 'Image added successfully !');
$imageName = $image->getFilename();
$fullSizeImgWebPath = $fileUploader->getTargetDirectory().'/'.$imageName;
[$width,$height] = getimagesize($fullSizeImgWebPath);
if($width > $height){
$width = 1500;
$height = 1000;
// $imageResize->writeThumbnail($fullSizeImgWebPath, 1500, 1000);
} else if($width == $height){
$width = 300;
$height = 300;
//$imageResize->writeThumbnail($fullSizeImgWebPath, 300, 300);
} else {
$width = 1500;
$height = 2254;
//$imageResize->writeThumbnail($fullSizeImgWebPath,1000,1600);
}
$imageResize->writeThumbnail($fullSizeImgWebPath, $width, $height);
return $this->redirectToRoute('admin_image');
}
return $this->render('admin/image/new_image.html.twig', [
'controller_name' => 'AdminImageController',
'form'=> $form->createView()
]);
}
I created a service to resize the uploaded image:
class ImageResizeService {
/**
* Write a thumbnail image using Imagine
*
* @param string $thumbAbsPath full absolute path to attachment directory e.g. /var/www/project1/images/thumbs/
*/
public function writeThumbnail($thumbAbsPath, $width, $height) {
$imagine = new Imagine;
$image = $imagine->open($thumbAbsPath);
$size = new Box($width, $height);
$image->thumbnail($size,ImageInterface::THUMBNAIL_OUTBOUND)
->save($thumbAbsPath);
}
}
Upvotes: 1