Generate a copy of image in different sizes

Submitted by yandine - 7 years ago

This script is for generating copies of uploaded images in different sizes. In my case I created a custom Library folder and then created a class FileUploader and add all functions that deals with any image uploads.

namespace App\Library ;

class FileUploader
{

public static function uploadImageWithCopies($path = null, $uploaded_file = null, $file_name = null, $custom_sizes = null)
    {
      try{          
              $imginfo_array  = getimagesize($uploaded_file); 

              $mime_type  = $imginfo_array['mime']; 
              
              if ($mime_type == "image/jpeg"){
                $src = imagecreatefromjpeg($uploaded_file);
              }else if($mime_type == "image/png"){
                $src = imagecreatefrompng($uploaded_file);
              }else if($mime_type == "image/gif"){
                $src = imagecreatefromgif($uploaded_file);
              }else{
                throw new Exception("Invalid Image");
              }
              //1 
              $inc=0; 
              $newwidth   =array(); 
              $newheight  =array();
              $tmp    =array();
              $location =array();
            foreach($custom_sizes as $cS){ 
              
              list($width,$height)  = getimagesize($uploaded_file);
              $newwidth[$inc]       = $cS['width'];
              $newheight[$inc]      = ($height/$width)*$newwidth[$inc];
              $tmp[$inc]          = imagecreatetruecolor($newwidth[$inc],$newheight[$inc]);
              imagecopyresampled($tmp[$inc],$src,0,0,0,0,$newwidth[$inc],$newheight[$inc],$width,$height);                      
              $location[$inc] = $path.$cS['prefixStr']. $file_name;
              
              $inc++;
            }
            $inc=0; 
            foreach($custom_sizes as $cS){
            if ($mime_type == "image/jpeg"){
              if (imagejpeg($tmp[$inc],$location[$inc],100)){}else{throw new Exception("Invalid Image");}
            }else if($mime_type == "image/png"){
                if (imagepng($tmp[$inc],$location[$inc],9)){}else{throw new Exception("Invalid Image");}
            }else if($mime_type == "image/gif"){
              if (imagegif($tmp[$inc],$location[$inc],9)){}else{throw new Exception("Invalid Image");}
            }else{
              throw new Exception("Invalid Image");
            }     
              $inc++;
            } 
            $inc=0; 
            foreach($custom_sizes as $cS){
              imagedestroy($tmp[$inc]);
              $inc++;
            }
              
    }
    catch(Exception $e){
      return false;
     
     }
  }
}