Esempio n. 1
3
 private function generateThumbnail($destination, $filename, $size)
 {
     $thumbDestination = $destination . $size . DS;
     if (!is_dir($thumbDestination)) {
         mkdir($thumbDestination, 0777, true);
     }
     $imageSettings = $this->getConfig();
     if (sizeof($imageSettings) == 0) {
         return false;
     }
     $thumb = new phpThumb();
     foreach ($imageSettings[$size] as $key => $value) {
         $thumb->setParameter($key, $value);
     }
     $thumb->setSourceData(file_get_contents($destination . $filename));
     if ($thumb->GenerateThumbnail()) {
         // this line is VERY important, do not remove it!
         if ($thumb->RenderToFile($thumbDestination . $filename)) {
             return true;
         } else {
             throw new Exception("Nie udało mi się wygenerować miniaturki o rozmiarze - {$size} Ponieważ:\n {$thumb->debugmessages}");
         }
     } else {
         throw new Exception("Błąd generatora\n {$thumb->debugmessages}");
     }
     return false;
 }
Esempio n. 2
0
function spit_phpthumb_image($filepath, $configarray = array())
{
    // set up class
    global $CFG, $PHPTHUMB_CONFIG;
    $phpThumb = new phpThumb();
    // import default config
    if (!empty($PHPTHUMB_CONFIG)) {
        foreach ($PHPTHUMB_CONFIG as $key => $value) {
            $keyname = 'config_' . $key;
            $phpThumb->setParameter($keyname, $value);
        }
    }
    // import passed params
    if (!empty($configarray)) {
        foreach ($configarray as $key => $value) {
            $keyname = $key;
            $phpThumb->setParameter($keyname, $value);
        }
    }
    $phpThumb->setSourceFilename($filepath);
    if (!is_file($phpThumb->sourceFilename) && !phpthumb_functions::gd_version()) {
        if (!headers_sent()) {
            // base64-encoded error image in GIF format
            $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
            header('Content-Type: image/gif');
            echo base64_decode($ERROR_NOGD);
        } else {
            echo '*** ERROR: No PHP-GD support available ***';
        }
        exit;
    }
    $phpThumb->SetCacheFilename();
    if (!file_exists($phpThumb->cache_filename) && is_writable(dirname($phpThumb->cache_filename))) {
        //         error_log("generating to cache: " . $phpThumb->cache_filename);
        $phpThumb->CleanUpCacheDirectory();
        $phpThumb->GenerateThumbnail();
        $phpThumb->RenderToFile($phpThumb->cache_filename);
    }
    if (is_file($phpThumb->cache_filename)) {
        //         error_log("sending from cache: " . $phpThumb->cache_filename);
        if ($getimagesize = @GetImageSize($phpThumb->cache_filename)) {
            $mimetype = phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]);
        }
        spitfile_with_mtime_check($phpThumb->cache_filename, $mimetype);
    } else {
        //         error_log("phpthumb cache file doesn't exist: " . $phpThumb->cache_filename);
        $phpThumb->GenerateThumbnail();
        $phpThumb->OutputThumbnail();
        exit;
    }
}
Esempio n. 3
0
 function thumb()
 {
     if (empty($_GET['src'])) {
         die("No source image");
     }
     //width
     $width = !isset($_GET['w']) ? 100 : $_GET['w'];
     //height
     $height = !isset($_GET['h']) ? 150 : $_GET['h'];
     //quality
     $quality = !isset($_GET['q']) ? 75 : $_GET['q'];
     $sourceFilename = WWW_ROOT . IMAGES_URL . $_GET['src'];
     if (is_readable($sourceFilename)) {
         App::import('Vendor', 'Phpthumb', array('file' => 'phpthumb' . DS . 'phpthumb.class.php'));
         $phpThumb = new phpThumb();
         $phpThumb->src = $sourceFilename;
         $phpThumb->w = $width;
         $phpThumb->h = $height;
         $phpThumb->q = $quality;
         $phpThumb->config_imagemagick_path = '/usr/bin/convert';
         $phpThumb->config_prefer_imagemagick = false;
         $phpThumb->config_output_format = 'png';
         $phpThumb->config_error_die_on_error = true;
         $phpThumb->config_document_root = '';
         $phpThumb->config_temp_directory = APP . 'tmp';
         $phpThumb->config_cache_directory = CACHE . 'thumbs' . DS;
         $phpThumb->config_cache_disable_warning = true;
         $cacheFilename = md5($_SERVER['REQUEST_URI']);
         $phpThumb->cache_filename = $phpThumb->config_cache_directory . $cacheFilename;
         // Check if image is already cached.
         if (!is_file($phpThumb->cache_filename)) {
             if ($phpThumb->GenerateThumbnail()) {
                 $phpThumb->RenderToFile($phpThumb->cache_filename);
             } else {
                 die('Failed: ' . $phpThumb->error);
             }
         }
         if (is_file($phpThumb->cache_filename)) {
             // If thumb was already generated we want to use cached version
             $cachedImage = getimagesize($phpThumb->cache_filename);
             header('Content-Type: ' . $cachedImage['mime']);
             readfile($phpThumb->cache_filename);
             exit;
         }
     } else {
         // Can't read source
         die("Couldn't read source image " . $sourceFilename);
     }
 }
Esempio n. 4
0
    function __construct(modX &$modx,array $config = array()) {
        $this->modx =& $modx;
        $this->config = array_merge(array(

        ),$config);
        parent::__construct();
    }
Esempio n. 5
0
 public static function thumbnail($image_path, $thumb_path, $image_name, $thumbnail_width = 0, $thumbnail_height = 0)
 {
     require_once JPATH_ROOT . '/jelibs/phpthumb/phpthumb.class.php';
     // create phpThumb object
     $phpThumb = new phpThumb();
     // this is very important when using a single object to process multiple images
     $phpThumb->resetObject();
     // set data source
     $phpThumb->setSourceFilename($image_path . DS . $image_name);
     // set parameters (see "URL Parameters" in phpthumb.readme.txt)
     if ($thumbnail_width) {
         $phpThumb->setParameter('w', $thumbnail_width);
     }
     if ($thumbnail_height) {
         $phpThumb->setParameter('h', $thumbnail_height);
     }
     $phpThumb->setParameter('zc', 'l');
     // set parameters
     $phpThumb->setParameter('config_output_format', 'jpeg');
     // generate & output thumbnail
     $output_filename = str_replace('/', DS, $thumb_path) . DS . 't-' . $thumbnail_width . 'x' . $thumbnail_height . '-' . $image_name;
     # .'_'.$thumbnail_width.'.'.$phpThumb->config_output_format;
     $capture_raw_data = false;
     if ($phpThumb->GenerateThumbnail()) {
         //			$output_size_x = ImageSX($phpThumb->gdimg_output);
         //			$output_size_y = ImageSY($phpThumb->gdimg_output);
         //			if ($output_filename || $capture_raw_data) {
         ////				if ($capture_raw_data && $phpThumb->RenderOutput()) {
         ////					// RenderOutput renders the thumbnail data to $phpThumb->outputImageData, not to a file or the browser
         ////					mysql_query("INSERT INTO `table` (`thumbnail`) VALUES ('".mysql_escape_string($phpThumb->outputImageData)."') WHERE (`id` = '".$id."')");
         ////				} elseif ($phpThumb->RenderToFile($output_filename)) {
         ////					// do something on success
         ////					echo 'Successfully rendered:<br><img src="'.$output_filename.'">';
         ////				} else {
         ////					// do something with debug/error messages
         ////					echo 'Failed (size='.$thumbnail_width.'):<pre>'.implode("\n\n", $phpThumb->debugmessages).'</pre>';
         ////				}
         //				$phpThumb->purgeTempFiles();
         //			} else {
         $phpThumb->RenderToFile($output_filename);
         //			}
     } else {
         // do something with debug/error messages
         //			echo 'Failed (size='.$thumbnail_width.').<br>';
         //			echo '<div style="background-color:#FFEEDD; font-weight: bold; padding: 10px;">'.$phpThumb->fatalerror.'</div>';
         //			echo '<form><textarea rows="10" cols="60" wrap="off">'.htmlentities(implode("\n* ", $phpThumb->debugmessages)).'</textarea></form><hr>';
     }
     return $output_filename;
 }
Esempio n. 6
0
function image_resize($image, $width, $height, $quality, $input_directory, $output_directory)
{
    $cache_dir = 'cache/';
    if ($input_directory !== '') {
        $source = $input_directory . $image;
    } else {
        $source = $image;
    }
    if ($output_directory !== '') {
        $target = $output_directory . $image;
    } else {
        $target = $image;
    }
    include_once DIR_FS_CATALOG . 'ext/phpthumb/phpthumb.class.php';
    // create phpThumb object
    $phpThumb = new phpThumb();
    // set data source -- do this first, any settings must be made AFTER this call
    $phpThumb->setSourceFilename($source);
    // set parameters (see "URL Parameters" in phpthumb.readme.txt)
    $phpThumb->setParameter('config_cache_directory', $cache_dir);
    if ($width !== '') {
        $phpThumb->setParameter('w', $width);
    } else {
        $phpThumb->setParameter('h', $height);
    }
    if ($quality !== '') {
        $phpThumb->setParameter('q', $quality);
    }
    // generate & output thumbnail
    if ($phpThumb->GenerateThumbnail()) {
        // this line is VERY important, do not remove it!
        if ($phpThumb->RenderToFile($target)) {
            // do something on success
            //		        echo 'Successfully rendered to "'.$image.'"';
        } else {
            // do something with debug/error messages
            echo 'Failed:<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre>';
        }
    } else {
        // do something with debug/error messages
        echo 'Failed:<pre>' . $phpThumb->fatalerror . "\n\n" . implode("\n\n", $phpThumb->debugmessages) . '</pre>';
    }
    // return $output;
}
Esempio n. 7
0
 static function uploadImages($field, $item, $delImage = 0, $itemType = 'albums', $width = 0, $height = 0)
 {
     $jFileInput = new JInput($_FILES);
     $file = $jFileInput->get('jform', array(), 'array');
     // If there is no uploaded file, we have a problem...
     if (!is_array($file)) {
         //			JError::raiseWarning('', 'No file was selected.');
         return '';
     }
     // Build the paths for our file to move to the components 'upload' directory
     $fileName = $file['name'][$field];
     $tmp_src = $file['tmp_name'][$field];
     $image = '';
     $oldImage = '';
     $flagDelete = false;
     //		$item = $this->getItem();
     // if delete old image checked or upload new file
     if ($delImage || $fileName) {
         $oldImage = JPATH_ROOT . DS . str_replace('/', DS, $item->images);
         // unlink file
         if (is_file($oldImage)) {
             @unlink($oldImage);
         }
         $flagDelete = true;
         $image = '';
     }
     $date = date('Y') . DS . date('m') . DS . date('d');
     $dest = JPATH_ROOT . DS . 'images' . DS . $itemType . DS . $date . DS . $item->id . DS;
     // Make directory
     @mkdir($dest, 0777, true);
     if (isset($fileName) && $fileName) {
         $filepath = JPath::clean($dest . $fileName);
         /*
         if (JFile::exists($filepath)) {
         	JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_FILE_EXISTS'));	// File exists
         }
         */
         // Move uploaded file
         jimport('joomla.filesystem.file');
         if (!JFile::upload($tmp_src, $filepath)) {
             JError::raiseWarning(100, JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE'));
             // Error in upload
             return '';
         }
         // if upload success, resize image
         if ($width) {
             require_once JPATH_ROOT . DS . 'jelibs/phpthumb/phpthumb.class.php';
             // create phpThumb object
             $phpThumb = new phpThumb();
             if (include_once JPATH_ROOT . DS . 'jelibs/phpthumb/phpThumb.config.php') {
                 foreach ($PHPTHUMB_CONFIG as $key => $value) {
                     $keyname = 'config_' . $key;
                     $phpThumb->setParameter($keyname, $value);
                 }
             }
             // this is very important when using a single object to process multiple images
             $phpThumb->resetObject();
             $phpThumb->setSourceFilename($filepath);
             // set parameters (see "URL Parameters" in phpthumb.readme.txt)
             $phpThumb->setParameter('w', $width);
             if ($height) {
                 $phpThumb->setParameter('h', $height);
             }
             $phpThumb->setParameter('config_output_format', 'jpeg');
             // set value to return
             $image = 'images/' . $itemType . '/' . str_replace(DS, '/', $date) . '/' . $item->id . '/' . $fileName;
             if ($phpThumb->GenerateThumbnail()) {
                 if ($image) {
                     if (!$phpThumb->RenderToFile($filepath)) {
                         // do something on failed
                         die('Failed (size=' . $width . '):<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre>');
                     }
                     $phpThumb->purgeTempFiles();
                 }
             } else {
                 // do something with debug/error messages
                 echo 'Failed (size=' . $width . ').<br>';
                 echo '<div style="background-color:#FFEEDD; font-weight: bold; padding: 10px;">' . $phpThumb->fatalerror . '</div>';
                 echo '<form><textarea rows="100" cols="300" wrap="off">' . htmlentities(implode("\n* ", $phpThumb->debugmessages)) . '</textarea></form><hr>';
                 die;
             }
         } else {
             // set value to return
             $image = 'images/' . $itemType . '/' . str_replace(DS, '/', $date) . '/' . $item->id . '/' . $fileName;
         }
     } else {
         if (!$flagDelete) {
             $image = $item->images;
         }
     }
     return $image;
 }
        @(list($key, $value) = explode('=', @$args[$i]));
        if (substr($key, -2) == '[]') {
            $_GET[substr($key, 0, -2)][] = $value;
        } else {
            $_GET[$key] = $value;
        }
    }
}
// instantiate a new phpThumb() object
ob_start();
if (!(include_once dirname(__FILE__) . '/phpthumb.class.php')) {
    ob_end_flush();
    die('failed to include_once("' . realpath(dirname(__FILE__) . '/phpthumb.class.php') . '")');
}
ob_end_clean();
$phpThumb = new phpThumb();
$phpThumb->DebugTimingMessage('phpThumb.php start', __FILE__, __LINE__, $starttime);
////////////////////////////////////////////////////////////////
// Debug output, to try and help me diagnose problems
$phpThumb->DebugTimingMessage('phpThumbDebug[0]', __FILE__, __LINE__);
if (@$_GET['phpThumbDebug'] == '0') {
    $phpThumb->phpThumbDebug();
}
////////////////////////////////////////////////////////////////
if (file_exists(dirname(__FILE__) . '/phpThumb.config.php')) {
    ob_start();
    if (include_once dirname(__FILE__) . '/phpThumb.config.php') {
        // great
    } else {
        ob_end_flush();
        $phpThumb->ErrorImage('failed to include_once(' . dirname(__FILE__) . '/phpThumb.config.php) - realpath="' . realpath(dirname(__FILE__) . '/phpThumb.config.php') . '"');
// Example of how to use phpthumb.class.php as an object    //
//                                                          //
//////////////////////////////////////////////////////////////
// Note: phpThumb.php is where the caching code is located, if
//   you instantiate your own phpThumb() object that code is
//   bypassed and it's up to you to handle the reading and
//   writing of cached files.
require_once '../phpthumb.class.php';
// create 3 sizes of thumbnail
$thumbnail_widths = array(160, 320, 640);
foreach ($thumbnail_widths as $thumbnail_width) {
    // Note: If you want to loop through and create multiple
    //   thumbnails from different image sources, you should
    //   create and dispose an instance of phpThumb() each time
    //   through the loop and not reuse the object.
    $phpThumb = new phpThumb();
    // set data
    $phpThumb->setSourceFilename($_FILES['userfile']['tmp_name']);
    // or $phpThumb->setSourceData($binary_image_data);
    // or $phpThumb->setSourceImageResource($gd_image_resource);
    // set parameters (see "URL Parameters" in phpthumb.readme.txt)
    $phpThumb->setParameter('w', $thumbnail_width);
    //$phpThumb->setParameter('h', 100);
    //$phpThumb->setParameter('fltr', 'gam|1.2');
    // set options (see phpThumb.config.php)
    // here you must preface each option with "config_"
    $phpThumb->setParameter('config_output_format', 'jpeg');
    $phpThumb->setParameter('config_imagemagick_path', '/usr/local/bin/convert');
    //$phpThumb->setParameter('config_allow_src_above_docroot', true); // needed if you're working outside DOCUMENT_ROOT, in a temp dir for example
    // generate & output thumbnail
    $output_filename = './thumbnails/' . basename($_FILES['userfile']['name']) . '_' . $thumbnail_width . '.' . $phpThumb->config_output_format;
Esempio n. 10
0
//        available at http://phpthumb.sourceforge.net     ///
//////////////////////////////////////////////////////////////
///                                                         //
// phpThumb.demo.object.php                                 //
// James Heinrich <*****@*****.**>                   //
//                                                          //
// Example of how to use phpthumb.class.php as an object    //
//                                                          //
//////////////////////////////////////////////////////////////
// Note: phpThumb.php is where the caching code is located, if
//   you instantiate your own phpThumb() object that code is
//   bypassed and it's up to you to handle the reading and
//   writing of cached files, if appropriate.
require_once '../phpthumb.class.php';
// create phpThumb object
$phpThumb = new phpThumb();
// create 3 sizes of thumbnail
$thumbnail_widths = array(160, 320, 640);
$capture_raw_data = false;
// set to true to insert to database rather than render to screen or file (see below)
foreach ($thumbnail_widths as $thumbnail_width) {
    // this is very important when using a single object to process multiple images
    $phpThumb->resetObject();
    // set data source -- do this first, any settings must be made AFTER this call
    $phpThumb->setSourceFilename('images/loco.jpg');
    // for static demo only
    //$phpThumb->setSourceFilename($_FILES['userfile']['tmp_name']);
    // or $phpThumb->setSourceData($binary_image_data);
    // or $phpThumb->setSourceImageResource($gd_image_resource);
    // PLEASE NOTE:
    // You must set any relevant config settings here. The phpThumb
Esempio n. 11
0
function uploadImg($clib, $chkT, $selR)
{
    global $cfg;
    global $l;
    if (!$cfg['upload']) {
        return false;
    }
    foreach ($_FILES['nfile']['size'] as $key => $size) {
        if ($size > 0) {
            // get file extension and check for validity
            $ext = pathinfo($_FILES['nfile']['name'][$key]);
            $ext = strtolower($ext['extension']);
            if (!in_array($ext, $cfg['valid'])) {
                // invalid image
                echo $l->m('er_029');
                return false;
            }
            $path = str_replace('//', '/', $cfg['root_dir'] . $clib);
            // remove double slash in path
            $nfile = fixFileName($_FILES['nfile']['name'][$key]);
            // remove invalid characters in filename
            // move file to temp directory for processing
            if (!move_uploaded_file($_FILES['nfile']['tmp_name'][$key], $cfg['temp'] . '/' . $nfile)) {
                // upload image to temp dir
                echo $l->m('er_028');
                return false;
            }
            $size = getimagesize($cfg['temp'] . '/' . $nfile);
            // process (thumbnail) images
            $arr = $cfg['thumbs'];
            foreach ($arr as $key => $thumb) {
                if (in_array($key, $chkT)) {
                    // create new phpThumb() object
                    require_once dirname(__FILE__) . '/phpThumb/phpthumb.class.php';
                    $phpThumb = new phpThumb();
                    // create object
                    // parameters
                    $phpThumb->config_cache_disable_warning = true;
                    // disable cache warning
                    $phpThumb->config_output_format = $ext;
                    // output format
                    $phpThumb->src = $cfg['temp'] . '/' . $nfile;
                    // destination
                    $phpThumb->q = 95;
                    // compression level for jpeg
                    if ($selR != '') {
                        // set auto rotate
                        $phpThumb->ar = $selR;
                    }
                    //-------------------------------------------------------------------------
                    if ($thumb['size'] > 0 && ($size[0] >= $thumb['size'] || $size[1] >= $thumb['size'])) {
                        // size value is set -> RESIZING and source image is larger than preset sizes
                        // resize parameters
                        if ($size[0] < $size[1]) {
                            // portrait
                            $phpThumb->h = $thumb['size'];
                            // max. height
                        } else {
                            $phpThumb->w = $thumb['size'];
                            // max. width
                        }
                        // crop parameters
                        if ($thumb['crop'] == true) {
                            $phpThumb->zc = 1;
                            // set zoom crop
                            $phpThumb->w = $thumb['size'];
                            // width
                            $phpThumb->h = $thumb['size'];
                            // height
                        }
                        // create file suffix
                        if ($thumb['ext'] == '*') {
                            // image size is used
                            $dim = '_' . $thumb['size'];
                            // e.g. _1280
                        } else {
                            if ($thumb['ext'] == '') {
                                // no suffix is created
                                $dim = '';
                            } else {
                                // suffix is set to $thumb['ext']
                                $dim = '_' . $thumb['ext'];
                            }
                        }
                        //-------------------------------------------------------------------------
                    } elseif ($thumb['size'] == 0 || $thumb['size'] == '*') {
                        // size value is set to '0' -> NO RESIZING
                        // crop parameters
                        if ($thumb['crop'] == true) {
                            $phpThumb->zc = 1;
                            // set zoom crop
                            if ($size[0] < $size[1]) {
                                // portrait
                                $phpThumb->w = $size[0];
                                // getimagesize width value
                                $phpThumb->h = $size[0];
                                // getimagesize width value
                            } else {
                                // landscape
                                $phpThumb->w = $size[1];
                                // getimagesize height value
                                $phpThumb->h = $size[1];
                                // getimagesize height value
                            }
                        }
                        // create file suffix
                        if ($thumb['ext'] == '*') {
                            // image size is used
                            $dim = '_' . ($size[0] <= $size[1] ? $size[1] : $size[0]);
                            // source height or width - e.g. _1280
                        } else {
                            if ($thumb['ext'] == '') {
                                // no suffix is created
                                $dim = '';
                            } else {
                                // suffix is set to $thumb['ext']
                                $dim = '_' . $thumb['ext'];
                            }
                        }
                        //-------------------------------------------------------------------------
                    } else {
                        // default setting - images smaller than predefined sizes
                        $dim = '';
                        // no file suffix is used
                    }
                    //-------------------------------------------------------------------------
                    $nthumb = fixFileName(basename($nfile, '.' . $ext) . $dim . '.' . $ext);
                    $nthumb = chkFileName($path, $nthumb);
                    // rename if file already exists
                    if ($phpThumb->GenerateThumbnail()) {
                        $phpThumb->RenderToFile($path . $nthumb);
                        @chmod($path . $nthumb, 0755) or die($l->m('er_028'));
                    } else {
                        // error
                        echo $l->m('er_028');
                        return false;
                    }
                    unset($phpThumb);
                }
            }
            @unlink($cfg['temp'] . '/' . $nfile);
            // delete temporary file
        }
    }
    return $nthumb;
}
Esempio n. 12
0
 /**
  * Create a thumbnail from an image, cache it and output it
  *
  * @param $imageName File name from webroot/uploads/
  */
 function thumbnail($imageName, $width = 120, $height = 120, $crop = 0)
 {
     $this->autoRender = false;
     $imageName = str_replace(array('..', '/'), '', $imageName);
     // Don't allow escaping to upper directories
     $width = intval($width);
     if ($width > 2560) {
         $width = 2560;
     }
     $height = intval($height);
     if ($height > 1600) {
         $height = 1600;
     }
     $cachedFileName = join('_', array($imageName, $width, $height, $crop)) . '.jpg';
     $cacheDir = Configure::read('Wildflower.thumbnailsCache');
     $cachedFilePath = $cacheDir . DS . $cachedFileName;
     $refreshCache = false;
     $cacheFileExists = file_exists($cachedFilePath);
     if ($cacheFileExists) {
         $cacheTimestamp = filemtime($cachedFilePath);
         $cachetime = 60 * 60 * 24 * 14;
         // 14 days
         $border = $cacheTimestamp + $cachetime;
         $now = time();
         if ($now > $border) {
             $refreshCache = true;
         }
     }
     if ($cacheFileExists && !$refreshCache) {
         return $this->_renderJpeg($cachedFilePath);
     } else {
         // Create cache and render it
         $sourceFile = Configure::read('Wildflower.uploadDirectory') . DS . $imageName;
         if (!file_exists($sourceFile)) {
             return trigger_error("Thumbnail generator: Source file {$sourceFile} does not exists.");
         }
         App::import('Vendor', 'phpThumb', array('file' => 'phpthumb.class.php'));
         $phpThumb = new phpThumb();
         $phpThumb->setSourceFilename($sourceFile);
         $phpThumb->setParameter('config_output_format', 'jpeg');
         $phpThumb->setParameter('w', intval($width));
         $phpThumb->setParameter('h', intval($height));
         $phpThumb->setParameter('zc', intval($crop));
         if ($phpThumb->GenerateThumbnail()) {
             $phpThumb->RenderToFile($cachedFilePath);
             return $this->_renderJpeg($cachedFilePath);
         } else {
             return trigger_error("Thumbnail generator: Can't GenerateThumbnail.");
         }
     }
 }
Esempio n. 13
0
    die('"magic_quotes_runtime" is set in php.ini, cannot run phpThumb with this enabled');
}
$starttime = array_sum(explode(' ', microtime()));
// this script relies on the superglobal arrays, fake it here for old PHP versions
if (phpversion() < '4.1.0') {
    $_SERVER = $HTTP_SERVER_VARS;
    $_GET = $HTTP_GET_VARS;
}
// instantiate a new phpThumb() object
ob_start();
if (!(include_once dirname(__FILE__) . '/phpthumb.class.php')) {
    ob_end_flush();
    die('failed to include_once("' . realpath(dirname(__FILE__) . '/phpthumb.class.php') . '")');
}
ob_end_clean();
$phpThumb = new phpThumb();
$phpThumb->DebugTimingMessage('phpThumb.php start', __FILE__, __LINE__, $starttime);
$phpThumb->SetParameter('config_error_die_on_error', true);
if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
    set_time_limit(60);
    // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
}
// phpThumbDebug[0] used to be here, but may reveal too much
// info when high_security_mode should be enabled (not set yet)
if (file_exists(dirname(__FILE__) . '/phpThumb.config.php')) {
    ob_start();
    if (include_once dirname(__FILE__) . '/phpThumb.config.php') {
        // great
    } else {
        ob_end_flush();
        $phpThumb->ErrorImage('failed to include_once(' . dirname(__FILE__) . '/phpThumb.config.php) - realpath="' . realpath(dirname(__FILE__) . '/phpThumb.config.php') . '"');
function aux_image($fieldValue, $params_image)
{
    $md5_params = md5($params_image);
    if (file_exists(MF_FILES_PATH . 'th_' . $md5_params . "_" . $fieldValue)) {
        $fieldValue = MF_FILES_URI . 'th_' . $md5_params . "_" . $fieldValue;
    } else {
        //generate thumb
        include_once dirname(__FILE__) . "/thirdparty/phpthumb/phpthumb.class.php";
        $phpThumb = new phpThumb();
        $phpThumb->setSourceFilename(MF_FILES_PATH . $fieldValue);
        $create_md5_filename = 'th_' . $md5_params . "_" . $fieldValue;
        $output_filename = MF_FILES_PATH . $create_md5_filename;
        $final_filename = MF_FILES_URI . $create_md5_filename;
        $params_image = explode("&", $params_image);
        foreach ($params_image as $param) {
            if ($param) {
                $p_image = explode("=", $param);
                $phpThumb->setParameter($p_image[0], $p_image[1]);
            }
        }
        if ($phpThumb->GenerateThumbnail()) {
            if ($phpThumb->RenderToFile($output_filename)) {
                $fieldValue = $final_filename;
            }
        }
    }
    return $fieldValue;
}
Esempio n. 15
0
 protected function getPhotoFromUrl($url, $size = null)
 {
     Yii::import('application.vendors.*');
     // Yii::import('ext.phpthumbnew.*');
     require_once '/phpthumb/phpthumb.class.php';
     // Yii::setPathOfAlias('phpthumb',Yii::getPathOfAlias('application.vendors.phpthumb.phpthumb.class.php'));
     $extention = 'jpg';
     $id_photo = time();
     $file_name = $id_photo . '.' . $extention;
     $upload_path = Yii::getPathOfAlias(Yii::app()->params['storeImages']['tmp']) . DIRECTORY_SEPARATOR . $file_name;
     $PT = new phpThumb();
     if ($size) {
         $sizes = explode('x', $size);
         $w = $sizes[0];
         $h = $sizes[1];
         $PT->w = (int) $w;
         $PT->h = (int) $h;
     }
     $PT->src = $url;
     $PT->bg = "#ffffff";
     $PT->q = 90;
     $PT->far = false;
     $PT->f = $extention;
     $PT->GenerateThumbnail();
     $success = $PT->RenderToFile($upload_path);
     if ($success) {
         return $id_photo . '.' . $extention;
     } else {
         return false;
     }
 }
<?php

//////////////////////////////////////////////////////////////
///  phpThumb() by James Heinrich <*****@*****.**>   //
//        available at http://phpthumb.sourceforge.net     ///
//////////////////////////////////////////////////////////////
///                                                         //
// phpThumb.demo.object.simple.php                          //
// James Heinrich <*****@*****.**>                   //
//                                                          //
// Simplified example of how to use phpthumb.class.php as   //
// an object -- please also see phpThumb.demo.object.php    //
//                                                          //
//////////////////////////////////////////////////////////////
require_once '../phpthumb.class.php';
$phpThumb = new phpThumb();
// set data
$phpThumb->setSourceFilename($_FILES['userfile']['tmp_name']);
// set parameters (see "URL Parameters" in phpthumb.readme.txt)
$phpThumb->setParameter('w', $thumbnail_width);
// generate & output thumbnail
$output_filename = './thumbnails/' . basename($_FILES['userfile']['name']) . '_' . $thumbnail_width . '.' . $phpThumb->config_output_format;
if ($phpThumb->GenerateThumbnail()) {
    // this line is VERY important, do not remove it!
    if ($phpThumb->RenderToFile($output_filename)) {
        // do something on success
        echo 'Successfully rendered to "' . $output_filename . '"';
    } else {
        // do something with debug/error messages
        echo 'Failed:<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre>';
    }
//                                                          //
//////////////////////////////////////////////////////////////
die('For security reasons, this demo is disabled by default. Please comment out line ' . __LINE__ . ' in ' . basename(__FILE__));
$ServerInfo['gd_string'] = 'unknown';
$ServerInfo['gd_numeric'] = 0;
//ob_start();
if (!(include_once '../phpThumb.functions.php')) {
    ob_end_flush();
    die('failed to include_once("../phpThumb.functions.php")');
}
if (!(include_once '../phpThumb.class.php')) {
    //ob_end_flush();
    die('failed to include_once("../phpThumb.class.php")');
}
//ob_end_clean();
$phpThumb = new phpThumb();
if (include_once '../phpThumb.config.php') {
    foreach ($PHPTHUMB_CONFIG as $key => $value) {
        $keyname = 'config_' . $key;
        $phpThumb->setParameter($keyname, $value);
    }
}
$ServerInfo['gd_string'] = phpThumb_functions::gd_version(true);
$ServerInfo['gd_numeric'] = phpThumb_functions::gd_version(false);
$ServerInfo['im_version'] = $phpThumb->ImageMagickVersion();
$gd_info = gd_info();
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
Esempio n. 18
0
            header('Location: ' . dirname($matches[1]) . '/' . urlencode(basename($matches[1])));
        } else {
            @readfile($phpThumb->cache_filename);
        }
        exit;
    }
    return true;
}
// instantiate a new phpThumb() object
ob_start();
if (!(include_once dirname(__FILE__) . '/phpthumb.class.php')) {
    ob_end_flush();
    die('failed to include_once("' . realpath(dirname(__FILE__) . '/phpthumb.class.php') . '")');
}
ob_end_clean();
$phpThumb = new phpThumb();
$phpThumb->DebugTimingMessage('phpThumb.php start', __FILE__, __LINE__, $starttime);
$phpThumb->SetParameter('config_error_die_on_error', true);
if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
    set_time_limit(60);
    // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
}
// phpThumbDebug[0] used to be here, but may reveal too much
// info when high_security_mode should be enabled (not set yet)
if (file_exists(dirname(__FILE__) . '/phpThumb.config.php')) {
    ob_start();
    if (include_once dirname(__FILE__) . '/phpThumb.config.php') {
        // great
    } else {
        ob_end_flush();
        $phpThumb->config_disable_debug = false;
Esempio n. 19
0
 /**
  * Run method with main page logic
  * 
  * Populate template and display form for editing an photo entry. For POST requests,
  * check user credentials, check if photo exists and then update entry in database.
  * Available to admins only
  * @access public
  */
 public function run()
 {
     $session = Session::getInstance();
     $user = $session->getUser();
     if (!$user || !$user->isAdmin()) {
         $session->setMessage("Do not have permission to access", Session::MESSAGE_ERROR);
         header("Location: " . BASE_URL);
         return;
     }
     $photoDAO = PhotoDAO::getInstance();
     $albumDAO = AlbumDAO::getInstance();
     $photo = null;
     $form_errors = array();
     $form_values = array("id" => "", "albumid" => "", "title" => "", "description" => "");
     if (!empty($_POST)) {
         $form_values["id"] = isset($_POST["id"]) && is_numeric($_POST["id"]) ? intval($_POST["id"]) : "";
         $form_values["albumid"] = isset($_POST["albumid"]) && is_numeric($_POST["albumid"]) ? intval($_POST["albumid"]) : "";
         $form_values["title"] = isset($_POST["title"]) ? trim($_POST["title"]) : "";
         $form_values["description"] = isset($_POST["description"]) ? trim($_POST["description"]) : "";
         if (empty($form_values["id"])) {
             $form_errors["id"] = "No id specified";
         }
         $photo = $photoDAO->load($form_values["id"]);
         if (!$photo) {
             $form_errors["id"] = "Photo does not exist";
         }
         if (empty($form_values["albumid"])) {
             $form_errors["albumid"] = "No albumid specified";
         } else {
             if (!$albumDAO->load($form_values["albumid"])) {
                 $form_errors["albumid"] = "Album does not exist";
             }
         }
         if (empty($form_values["title"])) {
             $form_errors["title"] = "No title specified";
         }
         if (empty($form_values["description"])) {
             $form_errors["description"] = "No description specified";
         }
         // Check if image will be changed
         $upload_path = "";
         if (!empty($_FILES["imagefile"]) && $_FILES["imagefile"]["error"] != UPLOAD_ERR_NO_FILE) {
             if ($_FILES["imagefile"]["error"] != UPLOAD_ERR_OK) {
                 $form_errors["imagefile"] = "File upload failed";
             } else {
                 $info = getimagesize($_FILES["imagefile"]["tmp_name"]);
                 $path = pathinfo($_FILES["imagefile"]["name"]);
                 $upload_path = joinPath(Photo::UPLOAD_DIR, strftime("%Y_%m"), basename($_FILES['imagefile']['name']));
                 $thumbLoc = joinPath(Photo::THUMBNAIL_DIR, strftime("%Y_%m"), $path["filename"] . "_thumb.jpg");
                 $smallThumbLoc = joinPath(Photo::THUMBNAIL_DIR, strftime("%Y_%m"), $path["filename"] . "_thumb_small.jpg");
                 if (!$info || !(strtolower($path["extension"]) != ".png" && strtolower($path["extension"]) != ".jpg" && strtolower($path["extension"]) != ".jpeg")) {
                     $form_errors["imagefile"] = "An invalid file was uploaded";
                 } else {
                     if (file_exists($upload_path)) {
                         unlink($upload_path);
                         if (file_exists($thumbLoc)) {
                             unlink($thumbLoc);
                         }
                         if (file_exists($smallThumbLoc)) {
                             unlink($smallThumbLoc);
                         }
                         //$form_errors["imagefile"] = "Filename already exists.  Please choose different name or delete file first";
                     }
                 }
             }
         }
         if (empty($form_errors)) {
             $photo->setAlbumId($form_values["albumid"]);
             $photo->setTitle($form_values["title"]);
             $photo->setDescription($form_values["description"]);
             // New image has been uploaded
             if (!empty($_FILES["imagefile"]) && $_FILES["imagefile"]["error"] != UPLOAD_ERR_NO_FILE) {
                 if (!file_exists(dirname($upload_path))) {
                     mkdir(dirname($upload_path));
                 }
                 if (move_uploaded_file($_FILES["imagefile"]["tmp_name"], $upload_path)) {
                     $photo->setFileLoc($upload_path);
                     // Reset thumbnail location in case new image does not need a thumbnail
                     $photo->setThumbLoc("");
                     // Create thumbnail
                     if ($info[0] > Photo::MAX_WIDTH) {
                         $phpThumb = new phpThumb();
                         $phpThumb->setSourceFilename($photo->getFileLoc());
                         $phpThumb->setParameter('w', Photo::MAX_WIDTH);
                         $phpThumb->setParameter('config_output_format', 'jpeg');
                         if (!file_exists(dirname($thumbLoc))) {
                             mkdir(dirname($thumbLoc));
                         }
                         if ($phpThumb->GenerateThumbnail() && $phpThumb->RenderToFile($thumbLoc)) {
                             $photo->setThumbLoc($thumbLoc);
                             $phpThumb = new phpThumb();
                             $phpThumb->setSourceFilename($photo->getFileLoc());
                             $phpThumb->setParameter('h', Photo::SMALL_THUMB_HEIGHT);
                             $phpThumb->setParameter('config_output_format', 'jpeg');
                             $phpThumb->GenerateThumbnail();
                         } else {
                             if (file_exists($photo->getFileLoc())) {
                                 unlink($photo->getFileLoc());
                             }
                             $form_errors["imagefile"] = "Image larger than " . Photo::MAX_WIDTH . "x" . Photo::MAX_HEIGHT . " and thumbnail generation failed";
                         }
                     }
                 } else {
                     $form_errors["imagefile"] = "File could not be moved";
                 }
             }
             if (empty($form_errors["imagefile"])) {
                 if ($photoDAO->save($photo)) {
                     $session->setMessage("Photo saved");
                     header("Location: edit_photo.php?id={$photo->getId()}");
                     return;
                 } else {
                     $session->setMessage("Photo not saved");
                 }
             }
         } else {
             if (empty($form_errors["id"])) {
                 $photo = $photoDAO->load($form_values["id"]);
             }
         }
     } else {
         if (!empty($_GET)) {
             $form_values["id"] = isset($_GET["id"]) ? $_GET["id"] : "";
             if (empty($form_values["id"])) {
                 header("Location: " . BASE_URL);
                 return;
             } else {
                 $photo = $photoDAO->load($form_values["id"]);
                 if ($photo) {
                     $form_values["id"] = $photo->getId();
                     $form_values["albumid"] = $photo->getAlbumId();
                     $form_values["title"] = $photo->getTitle();
                     $form_values["description"] = $photo->getDescription();
                 }
             }
         }
     }
     $album_array = $albumDAO->all();
     $this->template->render(array("title" => "Edit Photo", "session" => $session, "main_page" => "edit_photo_tpl.php", "photo" => $photo, "form_values" => $form_values, "form_errors" => $form_errors, "album_array" => $album_array));
 }
Esempio n. 20
0
 $messages[] = gettext("Attempting to upload icon file ...");
 $ul_username = run("users:id_to_name", $page_owner);
 $upload_folder = $textlib->substr($ul_username, 0, 1);
 $dir = $CFG->dataroot . "icons/" . $upload_folder . "/" . $ul_username . "/";
 if ($ok = $um->process_file_uploads($dir)) {
     if (!($imageattr = @getimagesize($um->get_new_filepath()))) {
         $ok = false;
         $messages[] = gettext("The uploaded icon file was invalid. Please ensure you are using JPEG, GIF or PNG files.");
     }
 }
 if ($ok == true) {
     if ($imageattr[0] > 100 || $imageattr[1] > 100) {
         // $ok = false;
         // $messages[] = gettext("The uploaded icon file was too large. Files must have maximum dimensions of 100x100.");
         require_once $CFG->dirroot . 'lib/iconslib.php';
         $phpThumb = new phpThumb();
         // import default config
         if (!empty($PHPTHUMB_CONFIG)) {
             foreach ($PHPTHUMB_CONFIG as $key => $value) {
                 $keyname = 'config_' . $key;
                 $phpThumb->setParameter($keyname, $value);
             }
         }
         $phpThumb->setSourceFilename($um->get_new_filepath());
         $phpThumb->w = 100;
         $phpThumb->h = 100;
         $phpThumb->config_output_format = 'jpeg';
         $phpThumb->config_error_die_on_error = false;
         if ($phpThumb->GenerateThumbnail()) {
             $phpThumb->RenderToFile($um->get_new_filepath());
             $imageattr[2] = "2";
Esempio n. 21
0
// ================================================
// iManager dialog - object method for phpThumb
// ================================================
// Developed: net4visions.com
// Copyright: net4visions.com
// License: LGPL - see license.txt
// (c)2005 All rights reserved.
// ================================================
// Revision: 1.0                   Date: 06/14/2005
// ================================================
//-------------------------------------------------------------------------
// include configuration settings
include dirname(__FILE__) . '/../config/config.inc.php';
// create new phpThumb() object
require_once dirname(__FILE__) . '/phpThumb/phpthumb.class.php';
$phpThumb = new phpThumb();
// set data
$phpThumb->setSourceFilename(str_replace('//', '/', $cfg['root_dir'] . $_REQUEST['src']));
$phpThumb->config_output_format = $_REQUEST['f'];
// format
$phpThumb->config_ttf_directory = dirname(__FILE__) . '/../fonts';
// ttf directory
$phpThumb->q = $_REQUEST['q'];
// quality
$phpThumb->config_error_die_on_error = true;
$phpThumb->config_cache_disable_warning = true;
// short form to get all the parameters:
/*
$allowedGETparameters = array('w', 'h', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bg', 'fltr', 'ra', 'ar', 'aoe', 'far', 'iar');
foreach ($_GET as $key => $value) {
	if (in_array($key, $allowedGETparameters)) {
Esempio n. 22
0
 if (!empty($_FILES['labelImage']) and $_FILES['labelImage']['size']) {
     // create upload object
     $image_upload = new simbio_file_upload();
     $image_upload->setAllowableFormat($sysconf['allowed_images']);
     $image_upload->setMaxSize($sysconf['max_image_upload'] * 1024);
     $image_upload->setUploadDir(IMAGES_BASE_DIR . 'labels');
     // upload
     $img_upload_status = $image_upload->doUpload('labelImage', $data['label_name']);
     if ($img_upload_status == UPLOAD_SUCCESS) {
         $data['label_image'] = $dbs->escape_string($image_upload->new_filename);
         // resize the image
         if (function_exists('imagecopyresampled')) {
             // we use phpthumb class to resize image
             include LIB_DIR . 'phpthumb/phpthumb.class.php';
             // create phpthumb object
             $phpthumb = new phpThumb();
             $phpthumb->new = true;
             $phpthumb->src = IMAGES_BASE_DIR . 'labels/' . $image_upload->new_filename;
             $phpthumb->w = 24;
             $phpthumb->h = 24;
             $phpthumb->f = 'png';
             $phpthumb->GenerateThumbnail();
             $temp_file = IMAGES_BASE_DIR . 'labels/' . 'temp-' . $image_upload->new_filename;
             $phpthumb->RenderToFile($temp_file);
             // remove original file and rename the resized image
             @unlink($phpthumb->src);
             @rename($temp_file, $phpthumb->src);
             unset($phpthumb);
         }
         // write log
         utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'bibliography', $_SESSION['realname'] . ' upload label image file ' . $image_upload->new_filename);
Esempio n. 23
0
 function imagePhpThumb($origpath, $destpath, $prefix, $filename, $ext, $width, $height, $quality, $size, $crop, $usewm, $wmfile, $wmop, $wmpos)
 {
     $lib = JPATH_SITE . DS . 'components' . DS . 'com_flexicontent' . DS . 'librairies' . DS . 'phpthumb' . DS . 'phpthumb.class.php';
     require_once $lib;
     unset($phpThumb);
     $phpThumb = new phpThumb();
     $filepath = $origpath . $filename;
     $phpThumb->setSourceFilename($filepath);
     $phpThumb->setParameter('config_output_format', "{$ext}");
     //if ( $ext=='gif' )  // Force maximum color for GIF images?
     //	$phpThumb->setParameter('fltr', 'rcd|256|1');
     $phpThumb->setParameter('w', $width);
     $phpThumb->setParameter('h', $height);
     if ($usewm == 1) {
         $phpThumb->setParameter('fltr', 'wmi|' . $wmfile . '|' . $wmpos . '|' . $wmop);
     }
     $phpThumb->setParameter('q', $quality);
     if ($crop == 1) {
         $phpThumb->setParameter('zc', 1);
     }
     $ext = pathinfo($filename, PATHINFO_EXTENSION);
     if (in_array($ext, array('png', 'ico', 'gif'))) {
         $phpThumb->setParameter('f', $ext);
     }
     $output_filename = $destpath . $prefix . $filename;
     if ($phpThumb->GenerateThumbnail()) {
         if ($phpThumb->RenderToFile($output_filename)) {
             return true;
         } else {
             echo 'Failed:<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre><br />';
             return false;
         }
     } else {
         echo 'Failed2:<pre>' . $phpThumb->fatalerror . "\n\n" . implode("\n\n", $phpThumb->debugmessages) . '</pre><br />';
         return false;
     }
 }
Esempio n. 24
0
// Live demo is at http://phpthumb.sourceforge.net/demo/    //
//                                                          //
//////////////////////////////////////////////////////////////
$ServerInfo['gd_string'] = 'unknown';
$ServerInfo['gd_numeric'] = 0;
//ob_start();
if (!(include_once '../phpthumb.functions.php')) {
    ob_end_flush();
    die('failed to include_once("../phpthumb.functions.php")');
}
if (!(include_once '../phpthumb.class.php')) {
    //ob_end_flush();
    die('failed to include_once("../phpthumb.class.php")');
}
//ob_end_clean();
$phpThumb = new phpThumb();
if (include_once '../phpThumb.config.php') {
    foreach ($PHPTHUMB_CONFIG as $key => $value) {
        $keyname = 'config_' . $key;
        $phpThumb->setParameter($keyname, $value);
    }
}
$ServerInfo['gd_string'] = phpthumb_functions::gd_version(true);
$ServerInfo['gd_numeric'] = phpthumb_functions::gd_version(false);
$ServerInfo['im_version'] = $phpThumb->ImageMagickVersion();
$gd_info = gd_info();
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
Esempio n. 25
0
 /**
  * Делает превьюшку
  * 
  * @param $thumbData {array}
  */
 function ddCreateThumb($thumbData)
 {
     //Вычислим размеры оригинаольного изображения
     $originalImg = array();
     list($originalImg['width'], $originalImg['height']) = getimagesize($thumbData['originalImage']);
     //Если хотя бы один из размеров оригинала оказался нулевым (например, это не изображение) — на(\s?)бок
     if ($originalImg['width'] == 0 || $originalImg['height'] == 0) {
         return;
     }
     //Пропрорции реального изображения
     $originalImg['ratio'] = $originalImg['width'] / $originalImg['height'];
     //Если по каким-то причинам высота не задана
     if ($thumbData['height'] == '' || $thumbData['height'] == 0) {
         //Вычислим соответственно пропорциям
         $thumbData['height'] = $thumbData['width'] / $originalImg['ratio'];
     }
     //Если по каким-то причинам ширина не задана
     if ($thumbData['width'] == '' || $thumbData['width'] == 0) {
         //Вычислим соответственно пропорциям
         $thumbData['width'] = $thumbData['height'] * $originalImg['ratio'];
     }
     //Если превьюшка уже есть и имеет нужный размер, ничего делать не нужно
     if ($originalImg['width'] == $thumbData['width'] && $originalImg['height'] == $thumbData['height'] && file_exists($thumbData['thumbName'])) {
         return;
     }
     $thumb = new phpThumb();
     //зачистка формата файла на выходе
     $thumb->setParameter('config_output_format', null);
     //Путь к оригиналу
     $thumb->setSourceFilename($thumbData['originalImage']);
     //Качество (для JPEG) = 100
     $thumb->setParameter('q', '100');
     //Разрешить ли увеличивать изображение
     $thumb->setParameter('aoe', $thumbData['allowEnlargement']);
     //Если нужно просто обрезать
     if ($thumbData['cropping'] == '1') {
         //Ширина превьюшки
         $thumb->setParameter('sw', $thumbData['width']);
         //Высота превьюшки
         $thumb->setParameter('sh', $thumbData['height']);
         //Если ширина оригинального изображения больше
         if ($originalImg['width'] > $thumbData['width']) {
             //Позиция по оси x оригинального изображения (чтобы было по центру)
             $thumb->setParameter('sx', ($originalImg['width'] - $thumbData['width']) / 2);
         }
         //Если высота оригинального изображения больше
         if ($originalImg['height'] > $thumbData['height']) {
             //Позиция по оси y оригинального изображения (чтобы было по центру)
             $thumb->setParameter('sy', ($originalImg['height'] - $thumbData['height']) / 2);
         }
     } else {
         //Ширина превьюшки
         $thumb->setParameter('w', $thumbData['width']);
         //Высота превьюшки
         $thumb->setParameter('h', $thumbData['height']);
         //Если нужно уменьшить + отрезать
         if ($thumbData['cropping'] == 'crop_resized') {
             $thumb->setParameter('zc', '1');
             //Если нужно пропорционально уменьшить, заполнив поля цветом
         } else {
             if ($thumbData['cropping'] == 'fill_resized') {
                 //Устанавливаем фон (без решётки)
                 $thumb->setParameter('bg', str_replace('#', '', $thumbData['backgroundColor']));
                 //Превьюшка должна точно соответствовать размеру и находиться по центру (недостающие области зальются цветом)
                 $thumb->setParameter('far', 'c');
             }
         }
     }
     //Создаём превьюшку
     $thumb->GenerateThumbnail();
     //Сохраняем в файл
     $thumb->RenderToFile($thumbData['thumbName']);
 }
 /**
  *	This function will do the actual work of creating a thumbnail image.
  *
  *	@param $width	The maximum width of the thumbnail.
  *	@param $height	The maximum height of the thumbnail.
  *	@param $cache	(optional) Indicate if the thumbnails should be cached. By default, caching is turned off.
  *
  *	@internal
  */
 function &_createThumbnail($width, $height, $cache = true)
 {
     // Check if the GD library is loaded.
     if (!extension_loaded('gd')) {
         $this->_error('YD_gd_not_installed');
     }
     // Include phpThumb
     require_once 'phpThumb/phpthumb.class.php';
     // Create a new thumbnail object
     $thumb = new phpThumb();
     $thumb->src = $this->getAbsolutePath();
     // Set the options for the creation of thumbnails
     $thumb->config_nohotlink_enabled = false;
     $thumb->config_cache_directory = YD_DIR_TEMP;
     // Set the width and the height
     $thumb->w = $width;
     $thumb->h = $height;
     // Create the cached thumbnail
     $cacheFName = $thumb->GenerateCachedFilename();
     $cacheFName .= $this->getLastModified();
     $cacheFName .= $this->getAbsolutePath();
     $cacheFName = YD_TMP_PRE . 'N_' . md5($cacheFName) . '.tmn';
     $cacheFName = YD_DIR_TEMP . '/' . $cacheFName;
     // Check if caching is enabled
     if ($cache == true) {
         // Output the cached version if any
         if (is_file($cacheFName)) {
             $img = new YDFSImage($cacheFName);
             header('Content-type: ' . $img->getMimeType());
             echo $img->getContents();
             die;
         }
     }
     // Width should be positive integer
     if ($width < 1) {
         $this->_error();
     }
     // Height should be positive integer
     if ($width < 1) {
         $this->_error();
     }
     // Generate the thumbnail
     $thumb->GenerateThumbnail();
     // Check if caching is enabled
     if ($cache == true) {
         $thumb->RenderToFile($cacheFName);
     }
     // Return the thumbnail object
     return $thumb;
 }
Esempio n. 27
0
 public function action_zip($articulo_id)
 {
     include DOCROOT . 'phpthumb/phpthumb.class.php';
     \Config::load('phpthumb');
     $document_root = str_replace("\\", "/", Config::get('document_root'));
     is_null($articulo_id) and Response::redirect('articulo');
     $articulo = Model_Articulo::find('first', array('related' => array('fotos', 'seccion'), 'where' => array(array('id', '=', $articulo_id))));
     $fotos_web = null;
     foreach ($articulo->fotos as $foto) {
         $phpThumb = new phpThumb();
         $phpThumb->setParameter('w', Config::get('web_size'));
         $phpThumb->setParameter('q', 75);
         $phpThumb->setParameter('aoe', true);
         $phpThumb->setParameter('config_output_format', 'jpeg');
         $phpThumb->setParameter('f', 'jpeg');
         $nombre_archivo = str_ireplace(".jpg", Config::get('photos_texto') . '.jpg', $foto->imagen);
         $pieces = explode("/", $nombre_archivo);
         $count_foto = count($pieces);
         $nombre_archivo = $pieces[$count_foto - 1];
         $output_filename = $document_root . "/web/" . $nombre_archivo;
         $phpThumb->setSourceData(file_get_contents($document_root . $foto->imagen));
         if ($phpThumb->GenerateThumbnail()) {
             if ($phpThumb->RenderToFile($output_filename)) {
                 Log::info('Imagen para web generada con exito' . $output_filename);
                 $fotos_web[] = $output_filename;
             } else {
                 Log::info('Error al generar imagen para web ' . $phpThumb->debugmessages);
             }
             $phpThumb->purgeTempFiles();
         } else {
             Log::info('Error Fatal al generar imagen para web ' . $phpThumb->fatalerror . "|" . $phpThumb->debugmessages);
         }
         unset($phpThumb);
     }
     $time = time();
     Zip::create_zip($fotos_web, $articulo_id, true, $time);
 }
Esempio n. 28
0
 public static function getPhpThumb()
 {
     $phpThumb = new \phpThumb();
     #$phpThumb->resetObject();
     $phpThumb->setParameter('config_disable_debug', FALSE);
     $phpThumb->setParameter('config_document_root', APP_ROOT);
     #$phpThumb->setParameter('config_high_security_enabled', TRUE);
     $phpThumb->setParameter('config_imagemagick_path', '/usr/bin/convert');
     $phpThumb->setParameter('config_allow_src_above_docroot', true);
     $phpThumb->setParameter('config_cache_directory', APP_ROOT . 'cache');
     $phpThumb->setParameter('config_temp_directory', APP_ROOT . 'cache');
     $phpThumb->setParameter('config_cache_prefix', 'phpThumb_cache');
     #$phpThumb->setParameter('config_cache_force_passthru', FALSE);
     #$phpThumb->setParameter('config_cache_maxage', NULL);
     #$phpThumb->setParameter('config_cache_maxsize', NULL);
     #$phpThumb->setParameter('config_cache_maxfile', NULL);
     $phpThumb->setParameter('config_cache_directory_depth', 3);
     return $phpThumb;
 }
Esempio n. 29
0
// Live demo is at http://phpthumb.sourceforge.net/demo/    //
//                                                          //
//////////////////////////////////////////////////////////////
$ServerInfo['gd_string'] = 'unknown';
$ServerInfo['gd_numeric'] = 0;
//ob_start();
if (!(include_once '../phpthumb.functions.php')) {
    //ob_end_flush();
    die('failed to include_once("../phpthumb.functions.php")');
}
if (!(include_once '../phpthumb.class.php')) {
    //ob_end_flush();
    die('failed to include_once("../phpthumb.class.php")');
}
//ob_end_clean();
$phpThumb = new phpThumb();
if (include_once '../phpThumb.config.php') {
    foreach ($PHPTHUMB_CONFIG as $key => $value) {
        $keyname = 'config_' . $key;
        $phpThumb->setParameter($keyname, $value);
    }
}
$ServerInfo['phpthumb_version'] = $phpThumb->phpthumb_version;
$ServerInfo['im_version'] = $phpThumb->ImageMagickVersion();
$ServerInfo['gd_string'] = phpthumb_functions::gd_version(true);
$ServerInfo['gd_numeric'] = phpthumb_functions::gd_version(false);
unset($phpThumb);
?>

<html>
<head>
Esempio n. 30
0
 }
 $cr_mw = 400;
 $cr_mh = 300;
 $d = $_REQUEST['d'] . '/' . md5($s . date("U")) . substr($s, strlen($s) - 4, 4);
 // create temporary file
 $sizes = @getimagesize($s);
 if ($sizes[0] > $cr_mw || $sizes[1] > $cr_mh) {
     if ($sizes[0] > $cr_mw) {
         $cr_f = $sizes[0] / $cr_mw;
     } else {
         $cr_f = $sizes[1] / $cr_mh;
     }
     $mw = $mw / $cr_f;
     $mh = $mh / $cr_f;
     include dirname(__FILE__) . '/../phpThumb/phpthumb.class.php';
     $phpThumb = new phpThumb();
     $phpThumb->src = $s;
     if ($sizes[0] < $sizes[1]) {
         // portrait
         $phpThumb->h = $cr_mh;
     } else {
         // landscape
         $phpThumb->w = $cr_mw;
     }
     $phpThumb->config_output_format = 'jpg';
     if ($phpThumb->GenerateThumbnail()) {
         $phpThumb->RenderToFile($d);
         $s = addslashes($d);
     } else {
         // do something with debug/error messages
         echo 'error_uploading';