src/EventListener/UploadListener.php line 9

  1. <?php
  2. namespace App\EventListener;
  3. use Vich\UploaderBundle\Event\Event;
  4. class UploadListener
  5. {
  6.     public function onVichUploaderPreUpload(Event $event): void
  7.     {
  8.         $object $event->getObject();
  9.         $file $object->file->getRealPath();
  10.         $type getimagesize($file);
  11.         if (true !== is_array($type)) {
  12.             return;
  13.         }
  14.         if (!strpos($type['mime'], 'png') && !strpos($type['mime'], 'jpeg') && !strpos($type['mime'], 'jpg') && !strpos($type['mime'], 'gif')) {
  15.             return;
  16.         }
  17.         $width $type[0] >= 900 900 $type[0];
  18.         $height $width * ($type[0] / $type[1]);
  19.         $this->_resizeImage($file$type$width$height);
  20.     }
  21.     private function _resizeImage($file$type$w$h$crop false): void
  22.     {
  23.         list($width$height) = getimagesize($file);
  24.         $r $width $height;
  25.         if ($crop) {
  26.             if ($width $height) {
  27.                 $width ceil($width - ($width abs($r $w $h)));
  28.             } else {
  29.                 $height ceil($height - ($height abs($r $w $h)));
  30.             }
  31.             $newwidth $w;
  32.             $newheight $h;
  33.         } else {
  34.             if ($w $h $r) {
  35.                 $newwidth $h $r;
  36.                 $newheight $h;
  37.             } else {
  38.                 $newheight $w $r;
  39.                 $newwidth $w;
  40.             }
  41.         }
  42.         if (strpos($type['mime'], 'png')) {
  43.             $src = @imagecreatefrompng($file);
  44.         } else {
  45.             $src = @imagecreatefromjpeg($file);
  46.         }
  47.         $dst imagecreatetruecolor($newwidth$newheight);
  48.         if (strpos($type['mime'], 'png')) {
  49.             // integer representation of the color black (rgb: 0,0,0)
  50.             $background imagecolorallocate($dst000);
  51.             // removing the black from the placeholder
  52.             imagecolortransparent($dst$background);
  53.             // turning off alpha blending (to ensure alpha channel information
  54.             // is preserved, rather than removed (blending with the rest of the
  55.             // image in the form of black))
  56.             imagealphablending($dstfalse);
  57.             // turning on alpha channel information saving (to ensure the full range
  58.             // of transparency is preserved)
  59.             imagesavealpha($dsttrue);
  60.             imagecopyresampled($dst$src0000$newwidth$newheight$width$height);
  61.             imagepng($dst$file);
  62.         } else {
  63.             imagecopyresampled($dst$src0000$newwidth$newheight$width$height);
  64.             imagejpeg($dst$file);
  65.         }
  66.         imagedestroy($dst);
  67.     }
  68. }