public function save($file, $type = IMAGETYPE_JPEG, $quality = 75,
                         $permissions = false) {

        // create directory if necessary
        $dir = dirname($file);
        if(!file_exists($dir)) {
            $mask = umask();
            mkdir($dir, 0777, true);
            umask($mask);
        }

        switch($type) {
            case IMAGETYPE_JPEG:
                imagejpeg($this->resource, $file, $quality);
                break;
            case IMAGETYPE_GIF:
                imagegif($this->resource, $file);
                break;
            case IMAGETYPE_PNG:
                imagepng($this->resource, $file);
                break;
            default:
                throw new Exception('Image type is not supported');
                break;
        }

        // change image rights
        if($permissions !== false) chmod($file, $permissions);

        // for method chaining
        return $this;
    }