resize() public method

include the Zebra_Image library require 'path/to/Zebra_Image.php'; instantiate the class $img = new Zebra_Image(); a source image $img->source_path = 'path/to/source.ext'; path to where should the resulting image be saved note that by simply setting a different extension to the file will instruct the script to create an image of that particular type $img->target_path = 'path/to/target.ext'; apply a "sharpen" filter to the resulting images $img->sharpen_images = true; resize the image to exactly 150x150 pixels, without altering aspect ratio, by using the CROP_CENTER method $img->resize(150, 150, ZEBRA_IMAGE_CROP_CENTER);
public resize ( integer $width, integer $height, integer $method = ZEBRA_IMAGE_CROP_CENTER, hexadecimal $background_color = '#FFFFFF' ) : boolean
$width integer The width to resize the image to. If set to 0, the width will be automatically adjusted, depending on the value of the height argument so that the image preserves its aspect ratio. If {@link preserve_aspect_ratio} is set to TRUE and both this and the height arguments are values greater than 0, the image will be resized to the exact required width and height and the aspect ratio will be preserved - (also see the description for the method argument below on how can this be done). If {@link preserve_aspect_ratio} is set to FALSE, the image will be resized to the required width and the aspect ratio will be ignored. If both width and height are set to 0, a copy of the source image will be created ({@link jpeg_quality} and {@link png_compression} will still apply). If either width or height are set to 0, the script will consider the value of the {@link preserve_aspect_ratio} to bet set to TRUE regardless of its actual value! @param integer $height The height to resize the image to. If set to 0, the height will be automatically adjusted, depending on the value of the width argument so that the image preserves its aspect ratio. If {@link preserve_aspect_ratio} is set to TRUE and both this and the width arguments are values greater than 0, the image will be resized to the exact required width and height and the aspect ratio will be preserved - (also see the description for the method argument below on how can this be done). If {@link preserve_aspect_ratio} is set to FALSE, the image will be resized to the required height and the aspect ratio will be ignored. If both width and height are set to 0, a copy of the source image will be created ({@link jpeg_quality} and {@link png_compression} will still apply). If either height or width are set to 0, the script will consider the value of the {@link preserve_aspect_ratio} to bet set to TRUE regardless of its actual value! @param int $method (Optional) Method to use when resizing images to exact width and height while preserving aspect ratio. If the {@link preserve_aspect_ratio} property is set to TRUE and both the width and height arguments are values greater than 0, the image will be resized to the exact given width and height and the aspect ratio will be preserved by using on of the following methods: - ZEBRA_IMAGE_BOXED - the image will be scalled so that it will fit in a box with the given width and height (both width/height will be smaller or equal to the required width/height) and then it will be centered both horizontally and vertically. The blank area will be filled with the color specified by the bgcolor argument. (the blank area will be filled only if the image is not transparent!) - ZEBRA_IMAGE_NOT_BOXED - the image will be scalled so that it could fit in a box with the given width and height but will not be enclosed in a box with given width and height. The new width/ height will be both smaller or equal to the required width/height - ZEBRA_IMAGE_CROP_TOPLEFT - ZEBRA_IMAGE_CROP_TOPCENTER - ZEBRA_IMAGE_CROP_TOPRIGHT - ZEBRA_IMAGE_CROP_MIDDLELEFT - ZEBRA_IMAGE_CROP_CENTER - ZEBRA_IMAGE_CROP_MIDDLERIGHT - ZEBRA_IMAGE_CROP_BOTTOMLEFT - ZEBRA_IMAGE_CROP_BOTTOMCENTER - ZEBRA_IMAGE_CROP_BOTTOMRIGHT For the methods involving crop, first the image is scaled so that both its sides are equal or greater than the respective sizes of the bounding box; next, a region of required width and height will be cropped from indicated region of the resulted image. Default is ZEBRA_IMAGE_CROP_CENTER @param hexadecimal $background_color (Optional) The hexadecimal color (like "#FFFFFF" or "#FFF") of the blank area. See the method argument. When set to -1 the script will preserve transparency for transparent GIF and PNG images. For non-transparent images the background will be white in this case. Default is #FFFFFF. @return boolean Returns TRUE on success or FALSE on error. If FALSE is returned, check the {@link error} property to see what went wrong
$height integer
$method integer
$background_color hexadecimal
return boolean
function laborator_img($url, $width = 0, $height = 0, $crop = FALSE)
{
    $upload_dir = wp_upload_dir();
    $post_thumbnail_url = '';
    $wpurl = site_url();
    $baseurl = $upload_dir['baseurl'];
    # Get Predefined Image Size
    if (is_string($width)) {
        $image_size = LaboratorImageSizes::get_img_size($width);
        extract($image_size);
    }
    # Get from post ID
    if (is_numeric($url)) {
        $post_thumbnail_id = get_post_thumbnail_id($url);
        if ($post_thumbnail_id) {
            $post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);
        } else {
            return '';
        }
    } else {
        $post_thumbnail_url = $url;
    }
    # Verify if its on this server
    if (strpos($post_thumbnail_url, $wpurl) != -1) {
        $relative_path = str_replace($wpurl, '', $post_thumbnail_url);
        $relative_path = ltrim($relative_path, '/');
        $absolute_path = ABSPATH . $relative_path;
        $basename = basename($absolute_path);
        # New Image Name
        $thumbnail_name = 'labimg_' . ($width ? "{$width}_" : '') . ($height ? "{$height}_" : '') . ($crop ? "1_" : '') . $basename;
        $thumbnail_path = dirname($absolute_path) . '/' . $thumbnail_name;
        $thumbnail_url = dirname($post_thumbnail_url) . '/' . $thumbnail_name;
        # Check if cached
        if (file_exists($thumbnail_path)) {
            return $thumbnail_url;
        }
        # Create File
        if (file_exists($absolute_path)) {
            # Generate Img
            $img = new Zebra_Image();
            $img->source_path = $absolute_path;
            $img->target_path = $thumbnail_path;
            $img->enlarge_smaller_images = TRUE;
            $img->preserve_aspect_ratio = TRUE;
            if ($crop) {
                $img->resize($width, $height, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
            } else {
                $img->resize($width, $height, ZEBRA_IMAGE_NOT_BOXED, '#FFF');
            }
            return $thumbnail_url;
        }
    }
    return '';
}
Beispiel #2
0
 static function thumb($name, $filename, $new_w, $new_h)
 {
     # create a new instance of the class
     $image = new Zebra_Image();
     # indicate a source image (a GIF, PNG or JPEG file)
     $image->source_path = $name;
     # indicate a target image
     # note that there's no extra property to set in order to specify the target
     # image's type -simply by writing '.jpg' as extension will instruct the script
     # to create a 'jpg' file
     $image->target_path = $filename;
     # since in this example we're going to have a jpeg file, let's set the output
     # image's quality (95% has no visible effect but saves some bytes)
     $image->jpeg_quality = 95;
     # some additional properties that can be set
     # read about them in the documentation
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = false;
     $image->preserve_time = true;
     # resize the image to at best 100x100 pixels by using the "not boxed" method
     # (read more in the overview section or in the documentation)
     # and if there is an error, check what the error is about
     if (!$image->resize($new_w, $new_h, ZEBRA_IMAGE_NOT_BOXED, -1)) {
         # only admins will see these errors
         if (JFactory::getUser()->authorise('core.manage')) {
             # if there was an error, let's see what the error is about
             switch ($image->error) {
                 case 1:
                     echo 'Source file could not be found!';
                     break;
                 case 2:
                     echo 'Source file is not readable!';
                     break;
                 case 3:
                     echo 'Could not write target file!';
                     break;
                 case 4:
                     echo 'Unsupported source file format!';
                     break;
                 case 5:
                     echo 'Unsupported target file format!';
                     break;
                 case 6:
                     echo 'GD library version does not support target file format!';
                     break;
                 case 7:
                     echo 'GD library is not installed!';
                     break;
             }
         }
         # if no errors
     } else {
         echo '';
     }
 }
Beispiel #3
0
 private function _uploadImage($sName)
 {
     if (isset($_FILES[$sName]) && $_FILES[$sName]['error'] == 0) {
         require_once ROOT . '/lib/Zebra_Image.php';
         $oZebra = new \Zebra_Image();
         $sImage = $this->config->templates->path . '/img/u/' . $_FILES[$sName]['name'];
         $oZebra->preserve_aspect_ratio = false;
         $oZebra->source_path = $_FILES[$sName]['tmp_name'];
         $oZebra->target_path = ROOT . $sImage;
         $oZebra->resize($this->config->image->width, $this->config->image->height, ZEBRA_IMAGE_BOXED);
         return $sImage;
     } else {
         return false;
     }
 }
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     Yii::import('application.libs.Zebra_Image.Zebra_Image');
     $model = $this->loadModel($id);
     if (isset($_POST['Residents'])) {
         $oldProfilePic = $model->profile_picture;
         $model->attributes = $_POST['Residents'];
         $model->scenario = "update";
         if (!empty($model->profile_picture) && strpos($model->profile_picture, ":image")) {
             /*process profile picture*/
             $foto = str_replace('data:image/png;base64,', '', $model->profile_picture);
             $foto = str_replace(' ', '+', $foto);
             $data_foto = base64_decode($foto);
             $currentUserFileName = sprintf("%s_%s_%s_%s", $model->firstname, $model->middle_name, $model->lastname, uniqid());
             $filename = $currentUserFileName . '.png';
             $filepath = YiiBase::getPathOfAlias("webroot.themes.abound.uploads") . '/' . $filename;
             $writeToDisk = file_put_contents($filepath, $data_foto);
             //remove extra space
             //
             $image = new Zebra_Image();
             $image->source_path = $filepath;
             $image->target_path = $filepath;
             $image->jpeg_quality = 100;
             $image->preserve_aspect_ratio = true;
             $image->enlarge_smaller_images = true;
             $image->preserve_time = true;
             $image->resize(300, 300, ZEBRA_IMAGE_CROP_TOPLEFT);
             //
             //
             $model->profile_picture = basename($filepath);
         } else {
             $model->profile_picture = $oldProfilePic;
         }
         /*proceed saving*/
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         } else {
             Yii::app()->user->setFlash("error", CHtml::errorSummary($model));
             $this->redirect(array('update', 'id' => $model->id));
         }
     }
     $this->render('update', array('residentRecord' => $model));
 }
Beispiel #5
0
 public function imageResize($source, $destination, $width, $height, $boxedType)
 {
     $image = new Zebra_Image();
     $image->source_path = $source;
     $image->target_path = $destination;
     $image->jpeg_quality = 90;
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = true;
     $image->preserve_time = true;
     if (!isset($boxedType)) {
         $boxedType = ZEBRA_IMAGE_NOT_BOXED;
     }
     if (!$image->resize($width, $height, $boxedType, '#FFFFFF')) {
         // if there was an error, let's see what the error is about
         switch ($image->error) {
             case 1:
                 echo 'Source file could not be found!';
                 break;
             case 2:
                 echo 'Source file is not readable!';
                 break;
             case 3:
                 echo 'Could not write target file!';
                 break;
             case 4:
                 echo 'Unsupported source file format!';
                 break;
             case 5:
                 echo 'Unsupported target file format!';
                 break;
             case 6:
                 echo 'GD library version does not support target file format!';
                 break;
             case 7:
                 echo 'GD library is not installed!';
                 break;
         }
         // if no errors
     } else {
         echo 'Success!';
     }
 }
 public function actionIndex()
 {
     Yii::import('application.libs.Zebra_Image.Zebra_Image');
     $residentRecord = new Residents("createNewRecord");
     if (Yii::app()->request->isPostRequest && $_POST['Residents']) {
         $oldProfilePic = $residentRecord->profile_picture;
         $residentRecord->attributes = $_POST['Residents'];
         if ($residentRecord->validate()) {
             //Decode with base64
             if (isset($residentRecord->profile_picture) && !empty($residentRecord->profile_picture) && !is_null($residentRecord->profile_picture)) {
                 $foto = str_replace('data:image/png;base64,', '', $residentRecord->profile_picture);
                 $foto = str_replace(' ', '+', $foto);
                 $data_foto = base64_decode($foto);
                 //Set photo filename
                 $currentUserFileName = sprintf("%s_%s_%s_%s", $residentRecord->firstname, $residentRecord->middle_name, $residentRecord->lastname, uniqid());
                 $filename = $currentUserFileName . '.png';
                 $filepath = YiiBase::getPathOfAlias("webroot.themes.abound.uploads") . '/' . $filename;
                 $writeToDisk = file_put_contents($filepath, $data_foto);
                 //remove extra space
                 $image = new Zebra_Image();
                 $image->source_path = $filepath;
                 $image->target_path = $filepath;
                 $image->jpeg_quality = 100;
                 $image->preserve_aspect_ratio = true;
                 $image->enlarge_smaller_images = true;
                 $image->preserve_time = true;
                 $image->resize(300, 300, ZEBRA_IMAGE_CROP_TOPLEFT);
                 $residentRecord->profile_picture = $filepath;
             }
             if ($residentRecord->save()) {
                 Yii::app()->user->setFlash("success", "<strong>Record Saved ! </strong>New Resident Record Created");
                 $this->redirect(array('/register'));
             }
         } else {
             Yii::app()->user->setFlash("error", CHtml::errorSummary($residentRecord));
         }
     }
     $this->render('index', compact('residentRecord'));
 }
Beispiel #7
0
 /**
  * Resize and/or crop an image
  *
  * @param $path
  * @param int $width
  * @param int $height
  * @param null $action
  * @return mixed
  * @throws InternalErrorException
  */
 public function resizeCrop($path, $width = 0, $height = 0, $action = null)
 {
     ini_set("memory_limit", "10000M");
     App::import('Vendor', 'Gallery.Zebra_Image', array('file' => 'ZebraImage.class.php'));
     # Flag
     $delete_png = false;
     $image = new Zebra_Image();
     # Load image
     $image->source_path = $path;
     # The target will be the same image
     $target = $path;
     # Get File Extension
     $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
     # Convert PNG files to JPG if configured on bootstrap.php
     if (Configure::read('GalleryOptions.Pictures.png2jpg') && $ext == "png") {
         # Flag to check must delete the png file
         $delete_png = true;
         # Store PNG file path to delete later
         $png_file = $target;
         # Update target path with JPG extension
         $target = str_replace(array('.png', '.PNG'), '.jpg', $path);
     }
     # The target will be the same image
     $image->target_path = $target;
     # JPG quality
     $image->jpeg_quality = Configure::read('GalleryOptions.Pictures.jpg_quality');
     # Extra configs
     $image->preserve_aspect_ratio = true;
     $image->enlarge_smaller_images = true;
     $image->preserve_time = true;
     if ($action == "crop") {
         $action = ZEBRA_IMAGE_CROP_CENTER;
     }
     if (!$image->resize($width, $height, $action)) {
         // if there was an error, let's see what the error is about
         switch ($image->error) {
             case 1:
                 throw new InternalErrorException('Source file could not be found!');
                 break;
             case 2:
                 throw new InternalErrorException('Source file is not readable!');
                 break;
             case 3:
                 throw new InternalErrorException('Could not write target file!');
                 break;
             case 4:
                 throw new InternalErrorException('Unsupported source file format!');
                 break;
             case 5:
                 throw new InternalErrorException('Unsupported target file format!');
                 break;
             case 6:
                 throw new InternalErrorException('GD library version does not support target file format!');
                 break;
             case 7:
                 throw new InternalErrorException('GD library is not installed!');
                 break;
             case 8:
                 throw new InternalErrorException('"chmod" command is disabled via configuration!');
                 break;
         }
     } else {
         # Delete PNG file if needed
         if ($delete_png) {
             unlink($png_file);
         }
         return $target;
     }
 }
 public function upload_image($files_instance)
 {
     if (!function_exists('wp_handle_upload')) {
         include_once ABSPATH . 'wp-admin/includes/file.php';
     }
     # Do Some Tricks...
     $_POST['action'] = 'simplead_handle_upload';
     $override['test_form'] = false;
     $override['action'] = 'simplead_handle_upload';
     $image_path = wp_handle_upload($files_instance, $override);
     $original_image = $image_path['file'];
     $images = array();
     if ($original_image) {
         // Generate Sizes
         foreach ($this->ad_sizes as $prefix => $size) {
             $w = $size[0];
             $h = $size[1];
             $new_file = dirname($file) . "/{$prefix}_" . basename($file);
             #$thumb = image_resize($original_image, $w, $h, true);
             $thumb = dirname($original_image) . "/{$prefix}_" . basename($original_image);
             # Zebra Image Ressize
             $img = new Zebra_Image();
             $img->enlarge_smaller_images = FALSE;
             $img->source_path = $original_image;
             $img->target_path = $thumb;
             $img->resize($w, $h, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
             $images[$prefix] = _wp_relative_upload_path($thumb);
         }
         $images['original'] = _wp_relative_upload_path($original_image);
     }
     return $images;
 }
Beispiel #9
0
function resizeImage(&$image, $request)
{
    if (!$image['result']) {
        return;
    }
    $resizeWidth = array_key_exists('resizeWidth', $request) ? $request['resizeWidth'] : false;
    $resizeHeight = array_key_exists('resizeHeight', $request) ? $request['resizeHeight'] : false;
    if ($resizeWidth === false && $resizeHeight === false) {
        return;
    }
    $zebraImage = new Zebra_Image();
    $zebraImage->source_path = $image['url'];
    $zebraImage->target_path = $image['url'];
    $zebraImage->jpeg_quality = 100;
    $image['result'] = $zebraImage->resize($resizeWidth, $resizeHeight, ZEBRA_IMAGE_CROP_CENTER);
    $image['status'] = extractZebraError($zebraImage);
}
Beispiel #10
0
 // set this to TRUE if you work on images uploaded by users
 // (see http://stefangabos.ro/wp-content/docs/Zebra_Image/Zebra_Image/Zebra_Image.html#var$auto_handle_exif_orientation)
 //$auto_handle_exif_orientation = true;
 // indicate a source image
 $image->source_path = 'images/transparent-png24.png';
 /**
  *
  *  THERE'S NO NEED TO EDIT BEYOUND THIS POINT
  *
  */
 $ext = substr($image->source_path, strrpos($image->source_path, '.') + 1);
 // indicate a target image
 $image->target_path = 'results/resize.' . $ext;
 // resize
 // and if there is an error, show the error message
 if (!$image->resize(100, 100, ZEBRA_IMAGE_BOXED, -1)) {
     show_error($image->error, $image->source_path, $image->target_path);
 }
 // from this moment on, work on the resized image
 $image->source_path = 'results/resize.' . $ext;
 // indicate a target image
 $image->target_path = 'results/flip-h.' . $ext;
 // flip horizontally
 // and if there is an error, show the error message
 if (!$image->flip_horizontal()) {
     show_error($image->error, $image->source_path, $image->target_path);
 }
 // indicate a target image
 $image->target_path = 'results/flip-v.' . $ext;
 // flip vertically
 // and if there is an error, show the error message
 public function generate_thumbnails($image_path, $image_sizes)
 {
     $files = array();
     # Checking if Image exists
     if (!file_exists($image_path)) {
     }
     #return array();
     $files['original'] = str_replace(ABSPATH, '', $image_path);
     $image_dir = dirname($image_path) . '/';
     $image_name = basename($image_path);
     $image_size = getimagesize($image_path);
     # Create Thumbnails
     foreach ($image_sizes as $prefix => $size) {
         $thumbnail_name = $prefix . $image_name;
         $thumbnail_path = $image_dir . $thumbnail_name;
         $width = $size[0];
         $height = $size[1];
         $crop = isset($size[2]);
         $boxed = isset($size[3]) ? $size[3] : 0;
         # Boxed to width and height
         # Resize only one dimension
         if ($width <= 0 || $height <= 0) {
             if ($height <= 0) {
                 # Resize by Width
                 $ratio = $width / $image_size[0];
                 $new_width = $width;
                 $new_height = $image_size[1] * $ratio;
             } else {
                 # Resize by Height
                 $ratio = $height / $image_size[1];
                 $new_width = $image_size[0] * $ratio;
                 $new_height = $height;
             }
             $width = $new_width;
             $height = $new_height;
         }
         # Rresize Image
         /* 
         	DEPRECATED METHOD
         	$thumbnail_path = image_resize($image_path, $width, $height, $crop, '', $thumbnail_path);
         */
         # Resize Image Using Zebra_Image Library
         $img = new Zebra_Image();
         $thumbnail_path = dirname($image_path) . "/{$prefix}_" . basename($image_path);
         $img->source_path = $image_path;
         $img->target_path = $thumbnail_path;
         if ($crop) {
             switch ($boxed) {
                 // Do not enlarge Smaller Images
                 case 2:
                     $img->enlarge_smaller_images = FALSE;
                     $img->resize($width, $height, ZEBRA_IMAGE_BOXED, '#FFF');
                     break;
                     // Fit images to box size
                 // Fit images to box size
                 case 1:
                 case TRUE:
                     $img->resize($width, $height, ZEBRA_IMAGE_BOXED, '#FFF');
                     break;
                     // Crop in the center
                 // Crop in the center
                 default:
                     $img->resize($width, $height, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
             }
         } else {
             $img->preserve_aspect_ratio = TRUE;
             $img->resize($width, $height, ZEBRA_IMAGE_NOT_BOXED, '#FFF');
         }
         $thumbnail_path_relative = str_replace(ABSPATH, '', $thumbnail_path);
         # Remove prefix last character which is _ or -
         $arr_index = preg_replace('/(_|-)$/', '', $prefix);
         $files[$arr_index] = $thumbnail_path_relative;
     }
     return $files;
 }
Beispiel #12
0
<?php

ini_set('display_errors', 'Off');
require_once '../class/Zebra_Image.php';
//SI LA IMAGEN SII SE LE REALIZO RESIZE ENTRA A ESTA FUNCION
if ($_REQUEST[hecerResize] == "1") {
    $img = new Zebra_Image();
    $img->source_path = "../upload/{$_REQUEST['imagen']}";
    $img->target_path = "../upload/temporal_{$_REQUEST['imagen']}";
    $img->sharpen_images = true;
    $img->jpeg_quality = 100;
    $img->preserve_aspect_ratio = true;
    $img->enlarge_smaller_images = true;
    $img->preserve_time = true;
    if ($img->resize(intval($_REQUEST[jrac_image_width]), intval($_REQUEST[jrac_image_height]), ZEBRA_IMAGE_CROP_CENTER)) {
        //PASAMOS A ROTAR LA IMAGEN
        require_once './rotate.php';
    } else {
        switch ($img->error) {
            case 1:
                echo 'Source file could not be found!';
                break;
            case 2:
                echo 'Source file is not readable!';
                break;
            case 3:
                echo 'Could not write target file!';
                break;
            case 4:
                echo 'Unsupported source file format!';
                break;
Beispiel #13
0
    $configs = $xoops->getModuleConfigs('thumbs');
    $imgWidth = $configs['thumbs_width'];
    $imgHeight = $configs['thumbs_height'];
}
$helper = $xoops->getModuleHelper('thumbs');
$thumbPath = $helper->buildThumbPath($imgPath, $imgWidth, $imgHeight);
$oldUmask = umask(022);
mkdir(dirname($xoops->path($thumbPath)), 0755, true);
umask($oldUmask);
$image = new Zebra_Image();
$image->source_path = $xoops->path($imgPath);
$image->target_path = $xoops->path($thumbPath);
$image->preserve_aspect_ratio = true;
$image->enlarge_smaller_images = false;
$image->preserve_time = true;
if ($image->resize($imgWidth, $imgHeight, ZEBRA_IMAGE_NOT_BOXED, -1)) {
    header("HTTP/1.1 301 Moved Permanently");
    header('Location: ' . $xoops->url($thumbPath));
} else {
    header("HTTP/1.0 404 Not Found");
    // http_response_code(400);
    // exit("Parameter error");
    switch ($image->error) {
        case 1:
            echo 'Source file could not be found!';
            break;
        case 2:
            echo 'Source file is not readable!';
            break;
        case 3:
            echo 'Could not write target file!';
Beispiel #14
0
 /**
  * Method to upload a file from client side, storing and making thumbnail for images
  *
  * TODO add token check for file uploading
  *
  * @return JSON
  */
 public function upload()
 {
     // Check for request forgeries
     if (!JSession::checkToken('request')) {
         die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_('JINVALID_TOKEN') . '"}, "id" : "id"}');
     }
     $user = JFactory::getUser();
     $srMedia = SRFactory::get('solidres.media.media');
     $date = JFactory::getDate();
     $model = $this->getModel('media');
     $err = NULL;
     $targetDir = SRPATH_MEDIA_IMAGE_SYSTEM;
     $targetThumbDir = SRPATH_MEDIA_IMAGE_SYSTEM . '/thumbnails';
     static $log;
     if ($log == null) {
         $options['format'] = '{DATE}\\t{TIME}\\t{LEVEL}\\t{CODE}\\t{MESSAGE}';
         $options['text_file'] = 'media.php';
         $log = JLog::addLogger($options);
     }
     JLog::add('Start uploading', JLog::DEBUG);
     if (!$user->authorise('core.create', 'com_solidres')) {
         JError::raiseWarning(403, JText::_('SR_ERROR_CREATE_NOT_PERMITTED'));
         return;
     }
     // HTTP headers for no cache etc
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Cache-Control: post-check=0, pre-check=0", false);
     header("Pragma: no-cache");
     // 5 minutes execution time
     @set_time_limit(5 * 60);
     // Uncomment this one to fake upload time
     // usleep(5000);
     // Get parameters
     $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
     $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
     $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
     JLog::add('Original file name ' . $fileName, JLog::DEBUG);
     // Clean the fileName for security reasons
     $_FILES['file']['name'] = JFile::makeSafe($_FILES['file']['name']);
     $fileName = $_FILES['file']['name'];
     JLog::add('Cleaned file name ' . $_FILES['file']['name'], JLog::DEBUG);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Check the target file against our rules to see if it is allow to be uploaded
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     // Do not check the chunk since it is not valid
     if (strpos($contentType, "multipart") !== false && $chunks == 0) {
         if (!SRMediaHelper::canUpload($_FILES['file'], $err)) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_($err) . '"}, "id" : "id"}');
             //return;
         }
     }
     // Make sure the fileName is unique but only if chunking is disabled
     if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
         $ext = strrpos($fileName, '.');
         $fileName_a = substr($fileName, 0, $ext);
         $fileName_b = substr($fileName, $ext);
         $count = 1;
         while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
             $count++;
         }
         $fileName = $fileName_a . '_' . $count . $fileName_b;
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($_FILES['file']['tmp_name'], "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     // ONLY PERFORM THESE LAST OPERATIONS WHEN THE FILE IS TOTALLY UPLOADED (NOT PARTLY UPLOADED)
     if ($chunks == 0 || $chunk == $chunks - 1) {
         $uploadedFilePath = $targetDir . '/' . $fileName;
         // Prepare some data for db storing
         $data = array('type' => 'IMAGE', 'value' => $fileName, 'name' => $fileName, 'created_date' => $date->toSql(), 'created_by' => $user->get('id'), 'mime_type' => $srMedia->getMime($uploadedFilePath), 'size' => filesize($uploadedFilePath));
         // Attempt to save the data.
         if (!$model->save($data)) {
             JLog::add('Can not save this file to db: ' . $fileName, JLog::DEBUG);
             die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "' . JText::_('SR_ERROR_CAN_NOT_SAVE_DB') . '"}, "id" : "id"}');
         }
         // If media is image, create thumbnail for it
         if (SRMediaHelper::isImage($uploadedFilePath)) {
             $media = new Zebra_Image();
             $media->source_path = $uploadedFilePath;
             $media->target_path = $targetThumbDir . '/1/' . $fileName;
             $media->resize(300, 250);
             $media->target_path = $targetThumbDir . '/2/' . $fileName;
             $media->resize(75, 75);
         }
     }
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }