View Single Post
Old 2018-02-07, 10:47 PM   #1
sarettah
Asleep at the switch? I wasn't asleep, I was drunk
 
Join Date: Apr 2005
Posts: 214
Batch optimizing and watermarking images using PHP

I shared this at the Zoo last month. Since I have been informed that I am a non-contributing so and so here, I figures I will share it here so I can then be a contributing so and so.

First, This requires PHP and the GD Libraries.

Optimize images class:

Code:
<?php 

namespace sarettahs_image_script;

// class to create optimized images and thumbnails from original images.  Sarettah 
// program expects image folder to be structured as image_folder/set_folder/image
// accepts jpg, gif or png input
// creates jpg, gif or png output

class optimize_images
{
  public $verbose=0;
  
  // optimized image dimensions
  public $maxheight=1000;
  public $maxwidth=1000;
  
  // thumb dimensions
  public $thumbheight=350;
  public $thumbwidth=350;
  
  // types of images to process
  public $imagelist='jpg,jpeg,gif,png';
  
  // type of image to create can be jpg, gif, png
  public $image_output='jpg';
  
  // folders to use
  public $base_dir='';
  public $optimized_dir='';
  public $thumb_dir='';

  // watermark image to use
  public $watermark='';

  // err report
  public $errmess='';

  // counts
  public $tot_files_made=0;
  public $tot_files_failed=0;
  public $tot_thumbs_made=0;
  public $tot_thumbs_failed=0;
  
  protected $make_thumbs=0;
  
  protected $folder_list=array();
  protected $file_list=array();

  protected $files_made=0;
  protected $files_failed=0;
  protected $thumbs_made=0;
  protected $thumbs_failed=0;

  
  public function mainline()
  {
    if(substr_count($this->imagelist,$this->image_output)==0)
    {
      $image_output='jpg';
    }
    // error out if base folder or optimized folder is not defined.
    if(empty($this->base_dir))
    {
      $this->errmess .="No Base Folder Defined<br>\n";
    }
    if(!is_dir($this->base_dir))
    {
      $this->errmess .="Base Folder " . $this->base_dir . " does not exist<br>\n";
    }

    if(empty($this->optimized_dir))
    {
      $this->errmess .="No Optimized Folder Defined<br>\n";
    }
    elseif(!is_dir($this->optimized_dir))
    {
      mkdir($this->optimized_dir);
      if(!is_dir($this->optimized_dir))
      {
        $this->errmess .="Could not create folder " . $this->optimized_dir . "<br>\n";
      }
    }

    // if no errors then go ahead and start it up
    if(empty($this->errmess))
    {
      // if thumb directory is defined then we will make thumbs      
      if(!empty($this->thumb_dir))
      {
        if(!is_dir($this->thumb_dir))
        {
          mkdir($this->thumb_dir);
        }
        if(!is_dir($this->thumb_dir))
        {
          $this->errmess .="Could not create folder " . $this->thumb_dir . "<br>\n";
          $this->make_thumbs=0;
        }
        else
        {
          $this->make_thumbs=1;
        }
      }
      else
      {
        $this->make_thumbs=0;
      }
      $this->process_images();
    }
  }
  
  protected function process_images()
  {
    set_time_limit(0);
    
    // get the folders inside the base folder
    $this->get_folders();
    if($this->verbose)
    {
      echo "found " . count($this->folder_list) . " folders<br>\n";
      flush();
    }
    
    // process through each folder in base folder for images
    foreach($this->folder_list as $folder)
    {
      if($this->verbose)
      {
        echo "Getting files for folder " . $folder . "<br>\n";
        flush();
      }
      $this->process_folder($this->base_dir, $folder);
    }
  }
  protected function process_folder($basedir, $folder)
  {
    $dir2use=$basedir . $folder . "/";      
    
    // get a list of the files in the folder
    $this->get_files($dir2use);
    if($this->verbose)
    {
      echo "Found " . count($this->file_list) . " files<br>\n";
      flush();
    }
    
    // initialize counters
    $this->files_made=0;
    $this->files_failed=0;
    $this->thumbs_made=0;
    $this->thumbs_failed=0;

    foreach($this->file_list as $image)
    {
      $this->make_optimized($dir2use, $image, $this->optimized_dir . $folder . '/', $this->maxheight, $this->maxwidth, $this->watermark);  
      $image2chk=substr($image,0,strrpos($image,'.')) . '.' . $this->image_output;
      if(is_file($this->optimized_dir . $folder . '/' . $image2chk))
      {
        $this->files_made++;
      }
      else
      {
        $this->files_failed++;
      }
      if($this->make_thumbs)
      {
        $this->make_optimized($dir2use, $image, $this->thumb_dir . $folder . '/', $this->thumbheight, $this->thumbwidth, $this->watermark);  
        $image2chk=substr($image,0,strrpos($image,'.')) . '.' . $this->image_output;
        if(is_file($this->thumb_dir . $folder . '/' . $image2chk))
        {
          $this->thumbs_made++;
        }
        else
        {
          $this->thumbs_failed++;
        }
      }
    }

    if($this->verbose)
    {
      echo "files made=" . $this->files_made . "<br>\n";
      echo "files failed=" . $this->files_failed . "<br>\n";
      echo "Thumbs made=" . $this->thumbs_made . "<br>\n";
      echo "Thumbs Failed=" . $this->thumbs_failed . "<br>\n";
    }
    
    $this->tot_files_made +=$this->files_made;
    $this->tot_files_failed +=$this->files_failed;
    $this->tot_thumbs_made +=$this->thumbs_made;
    $this->tot_thumbs_failed +=$this->thumbs_failed;
    
  }  

  protected function make_optimized($dir2use, $file_in, $newdir, $maxheight, $maxwidth, $watermark)
  { 
    $imagename=$dir2use . $file_in;

    // create new name using image extension
    $newname=substr($file_in,0,strrpos($file_in,'.')) . '.' . $this->image_output;
    $newname=$newdir . $newname;

    $width2use=0;
    $height2use=0;
    $ratio=0.0000;

    if(is_file($imagename))
    {
      $copyit=0;
      list($origwidth, $origheight, $type, $attr) = getimagesize($imagename);
      if($origwidth>0 && $origheight>0)
      {
        if($origheight<=$maxheight && $origwidth<=$maxwidth)
        {
          // if the image coming in is smaller than our optimized size then we just want to copy the image instead of re-sizing it
          $copyit=1;
        }

        // if the image coming in is smaller than our optimized size then we want to compute a ratio to use for re-sizing the image
        if($origheight>$origwidth)
        {
          if($origheight<$maxheight)
          {
            $maxheight=$origheight;
          }
          $ratio=$maxheight/$origheight;
          $width2use=$origwidth * $ratio;
          $height2use=$maxheight;
        }
        else
        {
          if($origwidth<$maxwidth)
          {
            $maxwidth=$origwidth;
          }
          $ratio=$maxwidth/$origwidth;
          $height2use=$origheight * $ratio;
          $width2use=$maxwidth;
        }     
        if(!is_dir($newdir))
        {
          mkdir($newdir);
        }
        if(is_dir($newdir))
        {      
          $right=20;
          $bottom=20;
            
          $imagestr=file_get_contents($imagename);
          $image2use=imagecreatefromstring($imagestr);
          $imagestr='';
          
          $use_watermark=0;
          if(!empty($watermark)  && is_file($watermark))
          {
            $use_watermark=1;
            $imagestr=file_get_contents($watermark);
            $watermark2use=imagecreatefromstring($imagestr);
            $imagestr='';
          }

          if($use_watermark)
          {
            // place watermark onto image
            imagecopy($image2use, $watermark2use, imagesx($image2use) - imagesx($watermark2use) - $right, imagesy($image2use) - imagesy($watermark2use) - $bottom, 0, 0, imagesx($watermark2use), imagesx($watermark2use));
          }
                      
          if($copyit)
          {
            // copy image without resizing it
            $this->make_image($image2use, $newname);
          }
          else
          {
            // copy image while resizing it
            $newimage = imagecreatetruecolor($width2use, $height2use);
            imagecopyresampled($newimage, $image2use, 0, 0, 0, 0, $width2use, $height2use, $origwidth, $origheight);
            $this->make_image($newimage, $newname);
            imagedestroy($newimage);
          }      
          imagedestroy($image2use);
          if($use_watermark)
          {
            imagedestroy($watermark2use);
          }

          if(!is_file($newname))
          {
            if($copyit)
            {
              $this->errmess .="Could not copy image " . $newname . "<br>\n";
            }
            else
            {
              $this->errmess .="Could not create image " . $newname . "<br>\n";
            }
          }
        }
        else
        {
          $this->errmess .="Could not create directory " . $newdir . "<br>\n";
        }        
      }
    }  
  }
  
  protected function make_image($image2use, $newname)
  {
    if($this->image_output=='jpg')
    {
      imagejpeg($image2use,$newname);
    }
    elseif($this->image_output=='gif')
    {
      imagegif($image2use,$newname);
    }
    elseif($this->image_output=='png')
    {
      imagepng($image2use,$newname);
    }
  }

  protected function get_folders()
  {
    $folderlist=scandir($this->base_dir);
    foreach($folderlist as $folder)
    {
      if(trim($folder)<>'..' && trim($folder)<>'.')
      {
        $path2chk=$this->base_dir . $folder . '/';
        if(is_dir($path2chk))
        {
          $this->folder_list[]=trim($folder);
        }
      }
    } 
  }

  protected function get_files($pathin)
  {
    if(is_dir($pathin))
    {
      $filelist=scandir($pathin);
      foreach($filelist as $file)
      {
        $file2chk=$pathin . $file;
        if(is_file($file2chk))
        {
          // only return image files
          if(substr_count($this->imagelist,strtolower(trim(pathinfo($file2chk)['extension'])))>0)
          {
            $this->file_list[]=trim($file);
          }
        }
      }
    } 
  }

}
?>
.
sarettah is offline   Reply With Quote