This class is responsible for making sure everything is set up and initialized properly, and returning the appropriate thumbnail class instance. It is the only recommended way of using this library, and if you try and circumvent it, the sky will fall on your head :) Basic use is easy enough. First, make sure all the settings meet your needs and environment... these are the static variables defined at the beginning of the class. Once that's all set, usage is pretty easy. You can simply do something like: $thumb = PhpThumbFactory::create('/path/to/file.png'); Refer to the documentation for the create function for more information
示例#1
0
 /**
  * Create a thumbnail of an image and returns relative path in webroot
  * the options array is an associative array which can take the values
  * quality (jpg quality) and method (the method for resizing)
  *
  * @param int $width
  * @param int $height
  * @param string $img
  * @param array $options
  * @return string $path
  */
 public static function create($width, $height, $img, $options = null)
 {
     if (!file_exists($img)) {
         throw new CException('Image not found');
     }
     // Defaults for options
     $thumbDir = '.tmb';
     $jpegQuality = 80;
     $resizeMethod = 'adaptiveResize';
     if ($options) {
         extract($options, EXTR_IF_EXISTS);
     }
     $pathinfo = pathinfo($img);
     $thumbName = 'thumb_' . $resizeMethod . '_' . $width . '_' . $height . '_' . $pathinfo['basename'];
     $thumbPath = $pathinfo['dirname'] . '/' . $thumbDir . '/';
     if (!file_exists($thumbPath)) {
         mkdir($thumbPath);
     }
     if (!file_exists($thumbPath . $thumbName) || filemtime($thumbPath . $thumbName) < filemtime($img)) {
         Yii::import('vendors.image.phpThumb.PhpThumbFactory');
         $options = array('jpegQuality' => $jpegQuality);
         $thumb = PhpThumbFactory::create($img, $options);
         $thumb->{$resizeMethod}($width, $height);
         $thumb->save($thumbPath . $thumbName);
     }
     return '/' . $thumbPath . $thumbName;
 }
示例#2
0
 function thumb($images, $pathUpload, $pathThumb, $thumbW, $thumbH = null, $crop = true)
 {
     //get array of image
     $images = unserialize($images);
     $thumbFile = array();
     $path = '';
     foreach ($images as $img) {
         $newPathThumb = null;
         //explode image by path seperate
         $tmp = explode('/', $img);
         //remove last element in array
         $imgFile = array_pop($tmp);
         //re-build path
         $path = implode('/', $tmp);
         $newPathThumb = $pathThumb . $path;
         $thumbFile[] = $path . '/thumbnail-' . $imgFile;
         //make dir if not exist
         if (!is_dir($newPathThumb)) {
             mkdir($newPathThumb, 0777, true);
         }
         $createThumbFile = $newPathThumb . '/thumbnail-' . $imgFile;
         //make thumb
         $file = $pathUpload . $img;
         if (!file_exists($createThumbFile) && is_file($file)) {
             $thumb = PhpThumbFactory::create($file);
             $thumb->resize($thumbW);
             if ($crop) {
                 $thumb->crop(0, 0, $thumbW, $thumbH);
             }
             $thumb->save($createThumbFile);
         }
     }
     return $thumbFile;
 }
示例#3
0
 protected function _beforeAdd(KCommandContext $context)
 {
     $container = $this->getModel()->container;
     if ($container instanceof ComFilesDatabaseRowContainer) {
         $size = $container->getParameters()->thumbnail_size;
         if (isset($size['x']) && isset($size['y'])) {
             $this->setThumbnailSize($size);
         }
     }
     @ini_set('memory_limit', '256M');
     $source = $context->data->file;
     if ($source) {
         try {
             $thumb = PhpThumbFactory::create($source);
         } catch (Exception $e) {
             // GD is not available
             return;
         }
         $thumb_size = $this->getThumbnailSize();
         $thumb->resize($thumb_size['x'], $thumb_size['y']);
         ob_start();
         echo $thumb->getImageAsString();
         $str = ob_get_clean();
         $str = sprintf('data:%s;base64,%s', 'image/png', base64_encode($str));
         $context->data->thumbnail_string = $str;
     }
 }
示例#4
0
 public function avatarUrl($size = false)
 {
     if ($size === false) {
         $size = Yii::app()->settings->get('users', 'avatar_size');
     }
     $ava = $this->avatar;
     if (!preg_match('/(http|https):\\/\\/(.*?)$/i', $ava)) {
         $r = true;
     } else {
         $r = false;
     }
     // if (!is_null($this->service)) {
     //     return $this->avatar;
     // }
     if ($size !== false && $r !== false) {
         $thumbPath = Yii::getPathOfAlias('webroot.assets.user_avatar') . DS . $size;
         if (!file_exists($thumbPath)) {
             mkdir($thumbPath, 0777, true);
         }
         // Path to source image
         $fullPath = Yii::getPathOfAlias('webroot.uploads.users.avatar') . DS . $ava;
         // Path to thumb
         $thumbPath = $thumbPath . DS . $ava;
         if (!file_exists($thumbPath)) {
             // Resize if needed
             Yii::import('ext.phpthumb.PhpThumbFactory');
             $sizes = explode('x', $size);
             $thumb = PhpThumbFactory::create($fullPath);
             $thumb->resize($sizes[0], $sizes[1])->save($thumbPath);
         }
         return empty($ava) ? '/uploads/users/avatars/user.png' : '/assets/user_avatar/' . $size . '/' . $ava;
     } else {
         return $ava;
     }
 }
示例#5
0
 public function actionUpload()
 {
     Yii::import("ext.MyAcrop.qqFileUploader");
     $folder = 'uploads/tmp';
     // folder for uploaded files
     // $allowedExtensions = array("jpg","jpeg","gif","png");
     $allowedExtensions = array();
     $sizeLimit = Yii::app()->params['storeImages']['maxFileSize'];
     $uploader = new qqFileUploader($allowedExtensions, $sizeLimit, $this->uploadlogosession);
     $uploader->inputName = 'photo';
     $result = $uploader->handleUpload($folder);
     $datasession = Yii::app()->session->itemAt($this->uploadlogosession);
     if (!empty($datasession)) {
         end($datasession);
         $key = key($datasession);
         $result['tmpFile'] = $datasession[$key];
         $tmpFile = Yii::getPathOfAlias('webroot') . '/uploads/tmp/' . $result['tmpFile'];
         if (file_exists($tmpFile)) {
             $thumbTo = array(160, 160);
             $folder = Yii::getPathOfAlias('webroot') . '/uploads/tmp/';
             $uploadDirectoryUpload = rtrim($folder, '/');
             $check = MHelper::File()->getUniqueTargetPath($uploadDirectoryUpload, $result['tmpFile']);
             $target = $uploadDirectoryUpload . '/' . $check;
             // if (copy($tmpFile, $target)){
             Yii::import('ext.phpthumb.PhpThumbFactory');
             $thumb = PhpThumbFactory::create($tmpFile);
             $sizes = Yii::app()->params['storeImages']['sizes'];
             $method = $sizes['resizeThumbMethod'];
             $thumb->{$method}($thumbTo[0], $thumbTo[1])->save($target);
             if (copy($target, $tmpFile)) {
                 unlink($target);
                 //delete tmp file
             }
             /* $result['tmpFile'] = $check;
                     
             
                                 $data_sess = array();
             
                                 if(Yii::app()->session->itemAt($this->uploadlogosession)){
                                     $data = Yii::app()->session->itemAt($this->uploadlogosession);
                                     if(!is_array($data)){
                                         $data_sess[$key] = $check;
                                     } else {
                                         $data[$key] = $check;
                                         $data_sess = $data;
                                     }
                                 } else {
                                     $data_sess[$key] = $check;
                                 }
                                 Yii::app()->session->remove($this->uploadlogosession);
                                 Yii::app()->session->add($this->uploadlogosession, $data_sess);
                                 
                                 unlink($tmpFile); //delete tmp file
                                 */
             // }
         }
     }
     $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
     echo $result;
 }
示例#6
0
	public function save()
	{
		if ($source = $this->source) {
			if (!is_file($source->fullpath) || !$source->isImage()) {
				return false;
			}

			$image = PhpThumbFactory::create($source->fullpath)
				->setOptions(array('jpegQuality' => 50))
				->adaptiveResize($this->_thumbnail_size, $this->_thumbnail_size);

			ob_start();

			echo $image->getImageAsString();

			$str = ob_get_clean();
			$str = sprintf('data:%s;base64,%s', $source->mimetype, base64_encode($str));

			$this->setData(array(
				'files_container_id' => $source->container->id,
				'folder' => '/'.$source->relative_folder,
				'filename' => $source->name,
				'thumbnail' => $str
			));
		}

		return parent::save();
	}
示例#7
0
 */
class ImageHelper
{
    /**
     * Directory to store thumbnails
     * @var string 
     */
    const THUMB_DIR = '.tmb';
    /**
     * Create a thumbnail of an image and returns relative path in webroot
     * the options array is an associative array which can take the values
     * quality (jpg quality) and method (the method for resizing)
     *
     * @param int $width
     * @param int $height
     * @param string $img
     * @param array $options
     * @return string $path
     */
    public static function thumb($width, $height, $img, $options = null)
    {
        if (!file_exists($img)) {
            $img = str_replace('\\', '/', YiiBase::getPathOfAlias('webroot') . $img);
            if (!file_exists($img)) {
                throw new ExceptionClass('Image not found');
            }
        }
        // Jpeg quality
        $quality = 80;
        // Method for resizing
        $method = 'adaptiveResize';
        if ($options) {
            extract($options, EXTR_IF_EXISTS);
        }
 public static function create_thumb($upload_path, $file_name, $file_ext)
 {
     $path = $upload_path . $file_name;
     $thumb_settings = Config::get('cms::theme.thumb');
     $thumb_options = Config::get('cms::settings.thumb_options');
     $thumb_path = $upload_path . Config::get('cms::settings.thumb_path');
     foreach ($thumb_settings as $setting) {
         $thumb = PhpThumbFactory::create(path('public') . $path, $thumb_options);
         if ($setting['method'] == 'resize') {
             $thumb->resize($setting['width'], $setting['height']);
         }
         if ($setting['method'] == 'adaptiveResize') {
             $thumb->adaptiveResize($setting['width'], $setting['height']);
         }
         if ($setting['method'] == 'cropFromCenter') {
             $thumb->cropFromCenter($setting['width'], $setting['height']);
         }
         //CREATE SUBDIR IF NOT EXISTS
         if (!file_exists(path('public') . $thumb_path)) {
             mkdir(path('public') . $thumb_path);
         }
         //CREATE THUMB FILE NAME
         $thumb_name = str_replace('.' . $file_ext, $setting['suffix'] . '.' . $file_ext, $file_name);
         $thumb->save(path('public') . $thumb_path . $thumb_name, $file_ext);
     }
     //return true;
     return '/' . $thumb_path . $thumb_name;
 }
示例#9
0
 /**
  * Get url to product image. Enter $size to resize image.
  * @param mixed $attr Model attribute
  * @param mixed $size New size of the image. e.g. '150x150'
  * @param mixed $dir Folder name upload
  * @return string
  */
 public function getImageUrl($attr, $dir, $size = false, $resize = 'resize')
 {
     Yii::import('ext.phpthumb.PhpThumbFactory');
     $attrname = $this->{$attr};
     if (!empty($attrname)) {
         if ($size !== false) {
             $thumbPath = Yii::getPathOfAlias('webroot.assets') . DS . $dir . DS . $size;
             if (!file_exists($thumbPath)) {
                 mkdir($thumbPath, 0777, true);
             }
             // Path to source image
             $fullPath = Yii::getPathOfAlias('webroot.uploads') . DS . $dir . DS . $attrname;
             // Path to thumb
             $thumbPath = $thumbPath . '/' . $attrname;
             if (!file_exists($thumbPath)) {
                 // Resize if needed
                 $sizes = explode('x', $size);
                 $thumb = PhpThumbFactory::create($fullPath);
                 $thumb->{$resize}($sizes[0], $sizes[1])->save($thumbPath);
                 //resize/adaptiveResize
             }
             return '/assets/' . $dir . '/' . $size . '/' . $attrname;
         }
         // return '/uploads/product/' . $attrname;
     } else {
         return false;
     }
 }
示例#10
0
function resize($image_url, $width, $height, $photoset_id = '')
{
    if ($image_url === FALSE) {
        return ar_default($width, $height, $photoset_id);
    }
    require_once APPPATH . 'third_party/phpthumb/ThumbLib.inc.php';
    $CI =& get_instance();
    $image_folder = $CI->config->item('RESIZED_IMAGES_PATH') . "{$photoset_id}/";
    $resized_images_url = $CI->config->item('RESIZED_IMAGES_URL') . "{$photoset_id}/";
    $size_folder = $width . "_" . $height;
    $image_name = basename($image_url);
    //return $image_folder.$size_folder;
    if (!file_exists($image_folder . $size_folder)) {
        mkdir($image_folder . $size_folder, 0755, true);
    }
    if (file_exists($image_folder . $size_folder . "/{$image_name}")) {
        return $resized_images_url . $size_folder . "/{$image_name}";
    }
    try {
        $thumb = PhpThumbFactory::create($image_url, array('jpegQuality' => 90));
        $thumb->resize($width, $height)->save($image_folder . $size_folder . "/{$image_name}");
        return $resized_images_url . $size_folder . "/{$image_name}";
    } catch (Exception $e) {
        return ar_default($width, $height, $photoset_id);
    }
    return '';
}
示例#11
0
function upload_image($image_field_name, $dir_path, $sizes)
{
    require_once 'phpthumb/ThumbLib.inc.php';
    $cnt = 1;
    $resized_path = $dir_path;
    if (!file_exists($dir_path)) {
        mkdir($dir_path);
        chmod($dir_path, 0755);
    }
    if (!file_exists($resized_path)) {
        mkdir($resized_path);
        chmod($resized_path, 0755);
    }
    if (!empty($_FILES[$image_field_name]['tmp_name'])) {
        $info = getimagesize($_FILES[$image_field_name]['tmp_name']);
        $originalfilename = basename($_FILES[$image_field_name]['name']);
        $imagetarget = resolve_filename_collisions($dir_path, array(basename($_FILES[$image_field_name]['name'])), $format = '%s_%d.%s');
        $originalfile = $dir_path . $imagetarget[0];
        if (move_uploaded_file($_FILES[$image_field_name]['tmp_name'], $originalfile)) {
            foreach ($sizes as $size) {
                $destinationfile = $resized_path . 'f' . $cnt++ . '_' . $imagetarget[0];
                $thumb = PhpThumbFactory::create($originalfile);
                $thumb->resize($size['width'], $size['height']);
                $thumb->save($destinationfile);
            }
            return $imagetarget[0];
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}
示例#12
0
 /**
  * Get url to product image. Enter $size to resize image.
  * @param mixed $size New size of the image. e.g. '150x150'
  * @param mixed $resizeMethod Resize method name to override config. resize/adaptiveResize
  * @param mixed $random Add random number to the end of the string
  * @return string
  */
 public function getUrl($size = false, $resizeMethod = false, $random = false)
 {
     if ($size !== false) {
         $thumbPath = Yii::getPathOfAlias(EventsImagesConfig::get('thumbPath')) . '/' . $size;
         if (!file_exists($thumbPath)) {
             mkdir($thumbPath, 0777, true);
         }
         // Path to source image
         $fullPath = Yii::getPathOfAlias(EventsImagesConfig::get('path')) . '/' . $this->image;
         // Path to thumb
         $thumbPath = $thumbPath . '/' . $this->image;
         if (!file_exists($thumbPath)) {
             // Resize if needed
             Yii::import('ext.phpthumb.PhpThumbFactory');
             $sizes = explode('x', $size);
             $thumb = PhpThumbFactory::create($fullPath);
             if ($resizeMethod === false) {
                 $resizeMethod = EventsImagesConfig::get('resizeThumbMethod');
             }
             $thumb->{$resizeMethod}($sizes[0], $sizes[1])->save($thumbPath);
         }
         return EventsImagesConfig::get('thumbUrl') . $size . '/' . $this->image;
     }
     if ($random === true) {
         return EventsImagesConfig::get('url') . $this->image . '?' . rand(1, 10000);
     }
     return EventsImagesConfig::get('url') . $this->image;
 }
示例#13
0
    public function generateThumbnail()
    {
		@ini_set('memory_limit', '256M');

    	if (($source = $this->getSource()) && $this->_canGenerate())
		{
            try
            {
				//Load the library
                require_once JPATH_LIBRARIES.'/koowa/components/com_files/helper/phpthumb/phpthumb.php';

                //Create the thumb
				$image = PhpThumbFactory::create($source->fullpath)
					->setOptions(array('jpegQuality' => 50));

                $size = $this->getSize();

				// Resize then crop to the provided resolution.
				$image->adaptiveResize($size['x'], $size['y']);

                ob_start();
				echo $image->getImageAsString();
				$str = ob_get_clean();
				$str = sprintf('data:%s;base64,%s', $source->mimetype, base64_encode($str));
				
				return $str;
			}
			catch (Exception $e) {
				return false;
			}
		}

		return false;
    }
示例#14
0
 /**
  * Get url to product image. Enter $size to resize image.
  * @param mixed $size New size of the image. e.g. '150x150'
  * @param mixed $resizeMethod Resize method name to override config. resize/adaptiveResize
  * @param mixed $random Add random number to the end of the string
  * @return string
  */
 public function getUrl($size = false, $resizeMethod = 'resize', $random = false)
 {
     // $config = Yii::app()->settings->get('shop');
     if ($size !== false) {
         $thumbPath = Yii::getPathOfAlias('webroot.assets.product') . '/' . $size;
         if (!file_exists($thumbPath)) {
             mkdir($thumbPath, 0777, true);
         }
         // Path to source image
         $fullPath = Yii::getPathOfAlias('webroot.uploads.product') . '/' . $this->name;
         // Path to thumb
         $thumbPath = $thumbPath . '/' . $this->name;
         if (!file_exists($thumbPath)) {
             // Resize if needed
             Yii::import('ext.phpthumb.PhpThumbFactory');
             $sizes = explode('x', $size);
             $thumb = PhpThumbFactory::create($fullPath);
             //  if ($resizeMethod === false)
             //   $resizeMethod = 'resize';
             $thumb->{$resizeMethod}($sizes[0], $sizes[1])->save($thumbPath);
         }
         return '/assets/product/' . $size . '/' . $this->name;
     }
     if ($random === true) {
         return '/uploads/product/' . $this->name . '?' . rand(1, 10000);
     }
     return '/uploads/product/' . $this->name;
 }
 public function generateThumbnail()
 {
     @ini_set('memory_limit', '256M');
     $source = $this->source;
     if ($source && !$source->isNew()) {
         try {
             //Load the library
             $this->getService('koowa:loader')->loadIdentifier('com://admin/files.helper.phpthumb.phpthumb');
             //Create the thumb
             $image = PhpThumbFactory::create($source->fullpath)->setOptions(array('jpegQuality' => 50));
             if ($this->_thumbnail_size['x'] && $this->_thumbnail_size['y']) {
                 // Resize then crop to the provided resolution.
                 $image->adaptiveResize($this->_thumbnail_size['x'], $this->_thumbnail_size['y']);
             } else {
                 $width = isset($this->_thumbnail_size['x']) ? $this->_thumbnail_size['x'] : 0;
                 $height = isset($this->_thumbnail_size['y']) ? $this->_thumbnail_size['y'] : 0;
                 // PhpThumb will calculate the missing side while preserving the aspect ratio.
                 $image->resize($width, $height);
             }
             ob_start();
             echo $image->getImageAsString();
             $str = ob_get_clean();
             $str = sprintf('data:%s;base64,%s', $source->mimetype, base64_encode($str));
             return $str;
         } catch (Exception $e) {
             return false;
         }
     }
     return false;
 }
function showImage()
{
    global $manager;
    $manager->load_helper("ThumbLib.inc");
    $thumb = PhpThumbFactory::create($_GET['mmfile']);
    $thumb->resize(100, 0);
    $thumb->show();
}
示例#17
0
 /**
  * Show image croped from center
  * @param string $fileName
  * @param int $width Image Width
  * @param int $height Image Height 
  */
 public function thumbCropFromCenter($fileName, $width = 160, $height = 110)
 {
     require_once 'thumb/ThumbLib.inc.php';
     $thumb = PhpThumbFactory::create(UPLOADS_PATH . DIRECTORY_SEPARATOR . $fileName);
     $thumb->cropFromCenter($width, $height);
     $thumb->show();
     //die();
 }
示例#18
0
 /**
  * Creates a new phpThumb object.
  * @param string $filePath the image file path.
  * @return PhpThumb object
  */
 protected static function thumbFactory($filePath)
 {
     try {
         return PhpThumbFactory::create($filePath, self::$_phpThumbOptions);
     } catch (Exception $e) {
         throw new CException($e->getMessage(), $e->getCode());
     }
 }
示例#19
0
 /**
  * Create image thumbnail object
  *
  * @param  string $filename
  * @param  array $options
  * @param  bool $isDataStream
  * @return type
  */
 public function create($filename = null, $options = array(), $isDataStream = false)
 {
     try {
         $thumb = \PhpThumbFactory::create($filename, $options, $isDataStream);
     } catch (\Exception $e) {
         throw new Exception\RuntimeException($e->getMessage(), $e->getCode(), $e);
     }
     return $thumb;
 }
 public function resize($image, $file, $width, $height, $type, $allow_up = false, $save_image = true)
 {
     $basePath = dirname(__FILE__) . '/../../libs/';
     $url = '';
     require_once $basePath . 'phpThumb/ThumbLib.inc.php';
     $options = array();
     if ($allow_up) {
         $options['resizeUp'] = true;
     }
     try {
         $GLOBALS['WiziappLog']->write('info', 'Before thumb resize: ' . $image, 'WiziappPhpThumbResizer.resize');
         $thumb = PhpThumbFactory::create($image, $options);
         //$thumb->$type($width, $height);
         if ($height == 0) {
             $type = 'resize';
             // Calc the new height based of the need to resize
             $dim = $thumb->getCurrentDimensions();
             $currWidth = $dim['width'];
             $currHeight = $dim['height'];
             if ($currWidth > $width) {
                 $height = $width / $currWidth * $currHeight;
             } else {
                 $height = $currHeight;
             }
             $GLOBALS['WiziappLog']->write('info', "Resizing from width: {$currWidth} to: {$width} and therefore from height: {$currHeight} to: {$height}", 'WiziappPhpThumbResizer.resize');
         } elseif ($width == 0) {
             $type = 'resize';
             // Calc the new height based of the need to resize
             $dim = $thumb->getCurrentDimensions();
             $currWidth = $dim['width'];
             $currHeight = $dim['height'];
             if ($currHeight > $height) {
                 $width = $height / $currHeight * $currWidth;
             } else {
                 $width = $currWidth;
             }
             $GLOBALS['WiziappLog']->write('info', "Resizing from height: {$currHeight} to: {$height} and therefore from width: {$currWidth} to: {$width}", 'WiziappPhpThumbResizer.resize');
         }
         $thumb->{$type}($width, $height);
         $size = $thumb->getCurrentDimensions();
         $this->newHeight = $size['height'];
         $this->newWidth = $size['width'];
         $this->thumb = $thumb;
         if ($save_image) {
             $thumb->save($file);
             // Convert the cache filesystem path to a public url
             $url = str_replace(WIZI_ABSPATH, get_bloginfo('wpurl') . '/', $file);
             $url = str_replace('\\', '/', $url);
         } else {
             $url = FALSE;
         }
         $GLOBALS['WiziappLog']->write('info', 'After thumb resize: ' . $image, 'WiziappPhpThumbResizer.resize');
     } catch (Exception $e) {
         $GLOBALS['WiziappLog']->write('error', 'Error resizing: ' . $e->getMessage(), 'WiziappPhpThumbResizer.resize');
     }
     return $url;
 }
示例#21
0
 public function create($file_location, $options = array())
 {
     try {
         require_once 'plugins/PHPThumbs/resources/ThumbLib.inc.php';
         return PhpThumbFactory::create($file_location, $options);
     } catch (Exception $e) {
         throw new PHPDS_exception($e->getMessage());
     }
 }
 /**
  * Generate thumbnail from provided file w/ specified size
  *
  * @param string $sourcePath
  * @param string $destPath
  * @param integer $width
  * @param integer $height
  * @param integer $quality
  */
 public function createThumbnail($sourcePath, $destPath, $width, $height, $quality = 100)
 {
     try {
         $thumb = PhpThumbFactory::create($sourcePath, array('jpegQuality' => $quality));
         $thumb->resize($width, $height);
         $thumb->save($destPath);
     } catch (Exception $e) {
         echo $e->getMessage();
     }
 }
示例#23
0
 /**
  * Crop an image using specific points where the crop have to begin.
  *
  * @param $from Origin file name
  * @param $to Final file name
  * @param $startX X point where the crop have to begin.
  * @param $startY Y point where the crop have to begin.
  * @param $width Final width.
  * @param $height Final height
  * @param bool $resizeUp
  * @param bool $transparency
  * @param int $quality
  * @return bool
  */
 public static function cropAndSave($from, $to, $startX, $startY, $width, $height, $resizeUp = false, $transparency = false, $quality = 100)
 {
     include_once ROOT_PATH . '/libs/' . Config::getInstance()->getLibrary('phpthumb') . '/ThumbLib.inc.php';
     $fileinfo = pathinfo($to);
     $thumb = \PhpThumbFactory::create($from);
     $thumb = \PhpThumbFactory::create($from, array('resizeUp' => $resizeUp, 'preserveAlpha' => $transparency, 'preserveTransparency' => $transparency, 'jpegQuality' => $quality));
     $thumb->crop($startX, $startY, $width, $height);
     $thumb->save($to, $fileinfo['extension']);
     return true;
 }
 public static function saveThumb($original_path, $thumb_path, $width, $height)
 {
     try {
         $thumb = PhpThumbFactory::create($original_path);
     } catch (Exception $e) {
         echo "Could not thumbnail file. Please contact Site Admin.";
         exit;
     }
     $thumb->resize($width, $height);
     $thumb->save($thumb_path);
 }
    public function run() {

        $controller = $this->getController();


         // get the Model Name
    	// $model_class = ucfirst($controller->getId());
 
    	// create the Model
    	// $model = new $model_class();
    	Yii::import("ext.MyAcrop.qqFileUploader");
        $folder='uploads/tmp';// folder for uploaded files
       // $allowedExtensions = array("jpg","jpeg","gif","png");
        $allowedExtensions = array();
        $sizeLimit = Yii::app()->params['storeImages']['maxFileSize'];
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit, 'articlefiles');
        $uploader->inputName = 'tmpFiles';
        $result = $uploader->handleUpload($folder);

        $datasession = Yii::app()->session->itemAt('articlefiles');

        if(!empty($datasession)){
                end($datasession);
                $key = key($datasession);
                $result['tmpFile'] = $datasession[$key];

                $tmpFile = Yii::getPathOfAlias('webroot').'/uploads/tmp/'.$result['tmpFile'];

        if(file_exists($tmpFile)) {

            $thumbTo = array(720,400);
            $folder = Yii::getPathOfAlias('webroot').'/uploads/tmp/';
            $uploadDirectoryUpload = rtrim($folder,'/');
            $check = MHelper::File()->getUniqueTargetPath($uploadDirectoryUpload, $result['tmpFile']);
            $target = $uploadDirectoryUpload.'/'.$check;
                
                Yii::import('ext.phpthumb.PhpThumbFactory');
                $thumb  = PhpThumbFactory::create($tmpFile);
                $sizes  = Yii::app()->params['storeImages']['sizes'];
               // $method = $sizes['resizeThumbMethod'];
               // $thumb->$method($thumbTo[0],$thumbTo[1])->save($target);
                $thumb->resize(1000)->save($target);

               if (copy($target, $tmpFile)){
                    unlink($target); //delete tmp file
               }
           }
       }
        $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        echo $result;

    }
示例#26
0
 protected function _getThumbObj($path)
 {
     if (empty($this->_loadedLibThumb)) {
         require_once JPATH_COMPONENT . '/asset/phpthumb/ThumbLib.inc.php';
         $this->_loadedLibThumb = true;
     }
     $signiture = serialize($path);
     if (empty($this->_objThumbs[$signiture])) {
         $this->_objThumbs[$signiture] = PhpThumbFactory::create($path);
     }
     return $this->_objThumbs[$signiture];
 }
示例#27
0
function atthumb_GET(Web &$w)
{
    $p = $w->pathMatch("id", array("w", 150), array("h", 150));
    $id = str_replace(".jpg", "", $p['id']);
    $attachment = $w->service("File")->getAttachment($id);
    require_once 'phpthumb/ThumbLib.inc.php';
    $thumb = PhpThumbFactory::create(FILE_ROOT . $attachment->fullpath);
    $thumb->resize($p['w'], $p['h']);
    //$thumb->adaptiveResize($p['w'], $p['h']);
    $thumb->show();
    exit;
}
 public function processRawFieldData($data, &$status, $simulate = false, $entry_id = NULL)
 {
     $status = self::__OK__;
     ## Its not an array, so just retain the current data and return
     if (!is_array($data)) {
         $status = self::__OK__;
         // Do a simple reconstruction of the file meta information. This is a workaround for
         // bug which causes all meta information to be dropped
         return array('file' => $data, 'mimetype' => self::__sniffMIMEType($data), 'size' => filesize(WORKSPACE . $data), 'meta' => serialize(self::getMetaInfo(WORKSPACE . $data, self::__sniffMIMEType($data))));
     }
     if ($simulate) {
         return;
     }
     if ($data['error'] == UPLOAD_ERR_NO_FILE || $data['error'] != UPLOAD_ERR_OK) {
         return;
     }
     ## Sanitize the filename
     $data['name'] = Lang::createFilename($data['name']);
     ## Resize image, if it's an image
     if (getimagesize($data['tmp_name'])) {
         try {
             $thumb = PhpThumbFactory::create($data['tmp_name']);
         } catch (Exception $e) {
             $message = __('There was an error while trying to resize the image <code>%1$s</code>.', array($data['name']));
             $status = self::__ERROR_CUSTOM__;
             return;
         }
         $thumb->resize($this->get('max_width'), $this->get('max_height'))->save($data['tmp_name']);
     }
     ## Upload the new file
     $abs_path = DOCROOT . '/' . trim($this->get('destination'), '/');
     $rel_path = str_replace('/workspace', '', $this->get('destination'));
     if (!General::uploadFile($abs_path, $data['name'], $data['tmp_name'], Symphony::Configuration()->get('write_mode', 'file'))) {
         $message = __('There was an error while trying to upload the file <code>%1$s</code> to the target directory <code>%2$s</code>.', array($data['name'], 'workspace/' . ltrim($rel_path, '/')));
         $status = self::__ERROR_CUSTOM__;
         return;
     }
     $status = self::__OK__;
     $file = rtrim($rel_path, '/') . '/' . trim($data['name'], '/');
     if ($entry_id) {
         $row = $this->Database->fetchRow(0, "SELECT * FROM `tbl_entries_data_" . $this->get('id') . "` WHERE `entry_id` = '{$entry_id}' LIMIT 1");
         $existing_file = rtrim($rel_path, '/') . '/' . trim(basename($row['file']), '/');
         if (strtolower($existing_file) != strtolower($file) && file_exists(WORKSPACE . $existing_file)) {
             General::deleteFile(WORKSPACE . $existing_file);
         }
     }
     ## If browser doesn't send MIME type (e.g. .flv in Safari)
     if (strlen(trim($data['type'])) == 0) {
         $data['type'] = 'unknown';
     }
     return array('file' => $file, 'size' => $data['size'], 'mimetype' => $data['type'], 'meta' => serialize(self::getMetaInfo(WORKSPACE . $file, $data['type'])));
 }
 public function formAction()
 {
     $smarty = Zend_Registry::get('view');
     $log = new SessionLAG();
     if ($log->_getTypeConnected('admin') || $log->_getTypeConnected('superadmin')) {
         $request = $this->getRequest();
         $id = (int) $request->getParam('id', 0);
         $form = $this->_getInformationForm($id);
         $model = $this->_getModel();
         if ($this->getRequest()->isPost()) {
             if ($form->isValid($request->getPost())) {
                 $dataform = $form->getValues();
                 if (empty($dataform['img'])) {
                     unset($dataform['img']);
                 } else {
                     $nom_image = $dataform["titre"];
                     require_once '../library/My/Utils.php';
                     $chaine_valide = valideChaine($nom_image);
                     $ext = explode('.', $dataform["img"]);
                     $ancien_nom = $dataform['img'];
                     $dataform['img'] = $chaine_valide . '.' . $ext[1];
                 }
                 $model->save($id, $dataform);
                 // resize picture si image dans formulaire
                 if (!empty($dataform['img'])) {
                     require_once '../library/My/PhpThumb/ThumbLib.inc.php';
                     $thumb = PhpThumbFactory::create('../public/images/info/' . $ancien_nom);
                     $thumb->adaptiveResize(475, 225)->save('../public/images/info/' . $dataform["img"]);
                     $thumb->adaptiveResize(75, 50)->save('../public/images/info/thumb/' . $dataform["img"]);
                     if (file_exists('../public/images/info/' . $ancien_nom)) {
                         unlink('../public/images/info/' . $ancien_nom);
                     }
                 }
                 return $this->_helper->redirector('indexadmin');
             }
         } else {
             if ($id > 0) {
                 $data = $model->fetchEntry($id);
                 $form->populate($data);
             }
         }
         if ($id > 0) {
             $smarty->assign('title', 'Modification Information');
         } else {
             $smarty->assign('title', 'Ajout Information');
         }
         $smarty->assign('form', $form);
         $smarty->display('information/form.tpl');
     } else {
         $smarty->display('error/errorconnexion.tpl');
     }
 }
示例#30
0
function thumb_image_scale($width = 1, $height = 1, $partrelative = null, $partfull = '')
{
    $link2 = explode('/', $partfull);
    $name1 = $partrelative . '/' . $width . '/' . $height . '/' . $link2[count($link2) - 1];
    $name1 = $width . '/' . $height . '/' . $partrelative . $link2[count($link2) - 1];
    if (!file_exists(SITE_DIR_BASE . $partfull) || $partfull == '') {
        $name1 = SITE_DIR_BASE . 'notfound.jpg';
    }
    $check1 = explode('.', $partfull);
    if (!in_array($check1[count($check1) - 1], array('jpg', 'png', 'jpeg', 'gif'))) {
        $link1 = '';
    } else {
        $bien = getimagesize(DOMAIN_BASE . $partfull);
        $wimg = isset($bien[0]) ? $bien[0] : 1;
        //chieu rong thuc te
        $himg = isset($bien[1]) ? $bien[1] : 1;
        // chieu cao thuc te
        $x = $wimg;
        $y = $himg;
        $h = floor($wimg * $height / $width);
        if ($h <= $himg) {
            $y = $h;
        } else {
            $x = floor($y * $width / $height);
        }
        if ($x <= $width) {
            $tl = 100;
        } else {
            $tl = 100 - floor(($x - $width) * 100 / $x);
        }
        $link2 = explode('/', $partfull);
        $link1 = makeDir($name1);
        $name = 'tmp_' . $width . "x" . $height . '_' . $link2[count($link2) - 1];
        $name1 = $link1;
        $link1 = $link1 . $name;
        $name1 .= $link2[count($link2) - 1];
        if (!file_exists(SITE_DIR_BASE . $link1)) {
            $thumb = PhpThumbFactory::create(DOMAIN_BASE . $partfull);
            $thumb->cropFromCenter($x, $y);
            //$thumb->resizePercent($tl);
            $thumb->save(SITE_DIR_BASE . $link1);
            $thumb = PhpThumbFactory::create(SITE_DIR_BASE . $link1);
            $thumb->resizePercent($tl);
            $thumb->save(SITE_DIR_BASE . $name1);
            @unlink(SITE_DIR_BASE . $link1);
            header('Content-Type: image/jpeg');
            readfile(SITE_DIR_BASE . $name1);
            exit;
        }
    }
    return $name1;
}