Example #1
0
 /**
  * Save the GD Image resource to disk
  *
  * @param   integer  $type     Type to save the image as. Default is source type.
  * @param   integer  $quality  Compression ration for jpg/png
  * @param   boolean  $target   Target directory. Defaults to sourcefolder/cache/
  * @return  object             Return current object to allow function chaining, false otherwise.
  */
 public function save($type = false, $quality = false, $target = false)
 {
     # Get the image type to save to. Blank space because IMAGETYPE_*** constants start at one.
     $type = $type ? $this->get_mime($type) : $this->type;
     $quality = $quality ?: $this->quality;
     # Build cache/filename and convert to hashstring if necessary.
     $cache = File::sanitize_path(dirname($target) ?: $this->img_cache);
     $fname = $target ?: $this->dst_filename . ($this->dimensions ? $this->separator . $this->separator . imagesx($this->img) . 'x' . imagesy($this->img) : '');
     $fname = $this->hashing ? hash('md5', $fname) : String::snake_case(File::sanitize_filename($fname));
     # Make sure cache directory exists with permissions
     if (File::dir_exists($cache, $this->perms)) {
         # Create src, URL and absolute image paths
         $fname = $cache . DIRECTORY_SEPARATOR . $fname . $this->extension[$type];
         $this->src = str_replace($this->docroot, '', $fname);
         $this->url = $this->protocol . $_SERVER['SERVER_NAME'] . $this->src;
         # If the file doesnt exist, or caching is disabled... create a new image.
         if (!file_exists($fname) || !$this->caching) {
             # Write the GD image resource to file
             switch ($type) {
                 case IMAGETYPE_JPEG:
                     # Convert a transparent background to the current transparent color
                     $this->fill($this->transbg);
                     $success = imageJPEG($this->img, $fname, $quality);
                     break;
                 case IMAGETYPE_GIF:
                     # Convert alpha transparency to indexed transparency.
                     if ($this->type === IMAGETYPE_PNG) {
                         $this->copytrans(true);
                     }
                     $success = imagegif($this->img, $fname);
                     break;
                 case IMAGETYPE_PNG:
                     $success = imagepng($this->img, $fname, min(round($quality / 10), 9));
                     break;
                 default:
                     throw new \Exception(__NAMESPACE__ . __CLASS__ . ": Can't save image to file. Unsupported image type.");
                     break;
             }
             return $success ? $this : false;
         }
     } else {
         # Cache can't be created.
         throw new \Exception(__NAMESPACE__ . __CLASS__ . ": Unable set image cache. Permissions?");
     }
     # Something went wrong... stop processing.
     return false;
 }