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; } }
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; }
/** * Resize an image * * Looks like a private function to me, but could be used as it is * * @param $filename String Nom du fichier * @param $options Array Can override $settings and add these options : * output : relative to 'folder' output image filename (default : $filename (overwrite)) * delete_source : if output is different from input, this set to true will delete the source file (default : false) * @return Returns true in case of success, false otherwise ($this->errors[$Model->name] gets populated) */ function resizeImage(&$Model, $filepath, $options = array()) { if (!file_exists($filepath)) { $this->errors[$Model->name][] = __('PhpThumb behavior : le fichier ', true) . $filepath . __(' n\'existe pas.', true); return false; } $settings = am(am($this->settings[$Model->name]['default'], array('output' => $filepath, 'delete_source' => false)), $options); App::import('Vendor', 'phpThumb', array('file' => 'phpThumb' . DS . 'phpthumb.class.php')); $phpThumb = new phpThumb(); $phpThumb->setSourceFilename($filepath); $phpThumb->setParameter('w', $settings['width']); $phpThumb->setParameter('h', $settings['height']); if ($settings['zoomcrop'] === true) { //$phpThumb->setParameter('zc', 1); } if (!(0 == $settings['sx'] && 0 == $settings['sy'] && 0 == $settings['sw'] && 0 == $settings['sh'])) { $phpThumb->setParameter('sx', $settings['sx']); $phpThumb->setParameter('sy', $settings['sy']); $phpThumb->setParameter('sw', $settings['sw']); $phpThumb->setParameter('sh', $settings['sh']); if ($settings['aoe']) { $phpThumb->setParameter('aoe', 1); } } if (isset($settings['f'])) { $phpThumb->setParameter('f', $settings['f']); } if (!$phpThumb->generateThumbnail()) { /* Woopsy, the image couldn't be resized */ debug($phpThumb->debugmessages); $this->errors[$Model->name][] = __('PhpThumb behavior : le fichier ', true) . $filepath . __(' n\'a pas pu être resizé', true); return false; } if (!$phpThumb->RenderToFile($settings['output'])) { /* File couldn't be created */ $this->errors[$Model->name][] = __('PhpThumb behavior : le fichier ', true) . $settings['folder'] . $settings['output'] . __(' n\'a pas pu être créé', true); return false; } if ($settings['delete_source'] && $settings['output'] != $filepath) { if (!unlink($filepath)) { $this->errors[$Model->name][] = __('PhpThumb behavior : le fichier ', true) . $filepath . __(' n\'a pas pu être supprimé', true); return false; } } return true; }
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; }
function get_image($fieldName, $groupIndex = 1, $fieldIndex = 1, $tag_img = 1) { require_once "RCCWP_CustomField.php"; global $wpdb, $post, $FIELD_TYPES; $fieldID = RCCWP_CustomField::GetIDByName($fieldName); $fieldObject = GetFieldInfo($fieldID); $fieldType = $wpdb->get_var("SELECT type FROM " . RC_CWP_TABLE_GROUP_FIELDS . " WHERE id='" . $fieldID . "'"); $single = true; switch ($fieldType) { case $FIELD_TYPES["checkbox_list"]: case $FIELD_TYPES["listbox"]: $single = false; break; } $fieldValues = (array) RCCWP_CustomField::GetCustomFieldValues($single, $post->ID, $fieldName, $groupIndex, $fieldIndex); if (!empty($fieldValues[0])) { $fieldValue = $fieldValues[0]; } else { return ""; } $url_params = explode("&", $fieldValue, 2); if (count($url_params) >= 2) { $fieldObject->properties['params'] .= "&" . $url_params[1]; $fieldValue = $url_params[0]; } if (substr($fieldObject->properties['params'], 0, 1) == "?") { $fieldObject->properties['params'] = substr($fieldObject->properties['params'], 1); } //check if exist params, if not exist params, return original image if (empty($fieldObject->properties['params']) && FALSE == strstr($fieldValue, "&")) { $fieldValue = FLUTTER_FILES_URI . $fieldValue; } else { //check if exist thumb image, if exist return thumb image $md5_params = md5($fieldObject->properties['params']); if (file_exists(FLUTTER_FILES_PATH . 'th_' . $md5_params . "_" . $fieldValue)) { $fieldValue = FLUTTER_FILES_URI . 'th_' . $md5_params . "_" . $fieldValue; } else { //generate thumb //include_once(FLUTTER_URI_RELATIVE.'thirdparty/phpthumb/phpthumb.class.php'); include_once dirname(__FILE__) . "/thirdparty/phpthumb/phpthumb.class.php"; $phpThumb = new phpThumb(); $phpThumb->setSourceFilename(FLUTTER_FILES_PATH . $fieldValue); $create_md5_filename = 'th_' . $md5_params . "_" . $fieldValue; $output_filename = FLUTTER_FILES_PATH . $create_md5_filename; $final_filename = FLUTTER_FILES_URI . $create_md5_filename; $params_image = explode("&", $fieldObject->properties['params']); 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; } } } } if ($tag_img) { $cssClass = $wpdb->get_results("SELECT CSS FROM " . RC_CWP_TABLE_GROUP_FIELDS . " WHERE name='" . $fieldName . "'"); if (empty($cssClass[0]->CSS)) { $finalString = stripslashes(trim("\\<img src=\\'" . $fieldValue . "\\' /\\>")); } else { $finalString = stripslashes(trim("\\<img src=\\'" . $fieldValue . "\\' class=\"" . $cssClass[0]->CSS . "\" \\/\\>")); } } else { $finalString = $fieldValue; } return $finalString; }
private function _thumbnail($maxwidth, $maxheight, $crop = false, $quality = 90) { $stack = $this->stack ? $this->stack : $this->resultset->get_stack(); if (!isset($this->thumbnails)) { $this->thumbnails = array(); } else { if (is_string($this->thumbnails)) { $this->thumbnails = array_filter(explode(';', $this->thumbnails)); } } $slugname = 'slug_' . language(); if (isset($this->{$slugname})) { $this->slug = $this->{$slugname}; } $file_path = get_file_directory(str_replace('>', '/', $stack)); $file_url = get_file_url(str_replace('>', '/', $stack)); $target = $this->id . '-' . intval($maxwidth) . 'x' . intval($maxheight); $extension = strtolower(substr($this->filename, strrpos($this->filename, '.') + 1)); $file = $this->slug . '-' . $this->id . '-' . intval($maxwidth) . '-' . intval($maxheight); $thumbcheck = language() . intval($maxwidth) . 'x' . intval($maxheight) . ($crop ? 'c' : ''); if ($crop) { $file .= '-c'; $target .= '-c'; } $file .= '.' . $extension; $target .= '.' . $extension; if (!in_array($thumbcheck, $this->thumbnails)) { $valid = true; if (strstr($this->filename, '://')) { if (!fopen($this->filename, "r")) { $valid = false; } } else { if (strstr($this->filename, $_SERVER['DOCUMENT_ROOT'])) { if (!file_exists($this->filename)) { $valid = false; } } else { if (!$this->filename || !file_exists(FILESPATH . $this->filename)) { $valid = false; } } } if (!$valid) { $this->filename = BASEPATH . 'nopic.jpg'; $file = $this->id . '-nopic-' . intval($maxwidth) . 'x' . intval($maxheight); $target = $this->id . '-nopic-' . intval($maxwidth) . 'x' . intval($maxheight); if ($crop) { $file .= '-c'; $target .= '-c'; } $file .= '.' . $extension; $target .= '.' . $extension; } require_once 'phpthumb/phpthumb.class.php'; $phpThumb = new phpThumb(); if (strstr($this->filename, '://') || strstr($this->filename, $_SERVER['DOCUMENT_ROOT'])) { $phpThumb->setSourceFilename($this->filename); } else { $phpThumb->setSourceFilename(FILESPATH . $this->filename); } $phpThumb->setParameter('w', $maxwidth); $phpThumb->setParameter('h', $maxheight); $phpThumb->setParameter('f', strtolower($extension)); if (is_numeric($quality)) { $phpThumb->setParameter('q', $quality); } else { $bytes = intval($quality); if (stristr($quality, 'mb')) { $bytes *= 1024 * 1024; } else { if (stristr($quality, 'kb')) { $bytes *= 1024; } } $phpThumb->setParameter('maxb', $bytes); } if ($crop) { $phpThumb->setParameter('zc', true); $phpThumb->setParameter('aoe', 1); $phpThumb->setParameter('far', 'C'); } $output_filename = $file_path . $target; $success = false; if (file_exists($output_filename)) { $success = true; } else { if ($phpThumb->GenerateThumbnail()) { $success = $phpThumb->RenderToFile($output_filename); } } if ($success) { @symlink($file_path . $target, $file_path . $file); if (!$this->path && $this->resultset) { $this->path = $this->resultset->get_stack(); } if ($this->id && $this->thumbnails_field && $this->path) { $this->thumbnails[] = $thumbcheck; where('id = %d', $this->id)->update($this->path, array($this->thumbnails_field => implode(';', $this->thumbnails))); } } } if ($crop) { $this->thumb_width = $maxwidth; $this->thumb_height = $maxheight; } else { $size = @getimagesize($file_path . $file); $this->thumb_width = $size[0]; $this->thumb_height = $size[1]; } return $file_url . $file; }
function file_cache_save_thumbnail_file($file_cache_r, &$errors) { $file_type_r = fetch_file_type_r($file_cache_r['content_type']); if ($file_type_r['thumbnail_support_ind'] == 'Y') { $sourceFile = file_cache_get_cache_file($file_cache_r); if ($sourceFile !== FALSE) { $phpThumb = new phpThumb(); // prevent issues with safe mode and /tmp directory //$phpThumb->setParameter('config_cache_directory', realpath('./itemcache')); $phpThumb->setParameter('config_error_die_on_error', FALSE); //$phpThumb->setParameter('config_prefer_imagemagick', FALSE); $phpThumb->setParameter('config_allow_src_above_docroot', TRUE); // configure the size of the thumbnail. if (is_array(get_opendb_config_var('item_display', 'item_image_size'))) { if (is_numeric(get_opendb_config_var('item_display', 'item_image_size', 'width'))) { $phpThumb->setParameter('w', get_opendb_config_var('item_display', 'item_image_size', 'width')); } else { if (is_numeric(get_opendb_config_var('item_display', 'item_image_size', 'height'))) { $phpThumb->setParameter('h', get_opendb_config_var('item_display', 'item_image_size', 'height')); } } } else { $phpThumb->setParameter('h', 100); } // input and output format should match $phpThumb->setParameter('f', $file_type_r['extension']); $phpThumb->setParameter('config_output_format', $file_type_r['extension']); $phpThumb->setSourceFilename(realpath($sourceFile)); $directory = realpath(file_cache_get_cache_type_directory($file_cache_r['cache_type'])); $thumbnailFile = $directory . '/' . $file_cache_r['cache_file_thumb']; if ($phpThumb->GenerateThumbnail() && $phpThumb->RenderToFile($thumbnailFile)) { opendb_logger(OPENDB_LOG_INFO, __FILE__, __FUNCTION__, 'Thumbnail image saved', array($sequence_number, $cache_type, $file_type_r, $thumbnailFile)); return TRUE; } else { // do something with debug/error messages if (is_not_empty_array($phpThumb->debugmessages)) { $errors = $phpThumb->debugmessages; } else { if (strlen($phpThumb->debugmessages) > 0) { // single array element $errors[] = $phpThumb->debugmessages; } } opendb_logger(OPENDB_LOG_ERROR, __FILE__, __FUNCTION__, implode(";", $errors), array($file_cache_r, $file_type_r, $file_cache_r['cache_file_thumb'])); return FALSE; } } else { //if(is_file opendb_logger(OPENDB_LOG_ERROR, __FILE__, __FUNCTION__, 'Source image not found', array($file_cache_r, $file_type_r, $sourceFile)); return FALSE; } } else { opendb_logger(OPENDB_LOG_ERROR, __FILE__, __FUNCTION__, 'Thumbnails not supported by image file type', array($file_cache_r, $file_type_r)); return FALSE; } }
/** * Делает превьюшку * * @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']); }
/** * 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."); } } }
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; }
/** * Creation of an image thumbnail * * @param $name String File name on server * @param $filename String Final file name * @param $new_w Int Width in px * @param $new_h Int Height in px * @param $zc Bool "Zoom crop" (if true, cuts the largest possible square from the image center) */ function createthumb($name, $filename, $new_w, $new_h, $zc) { App::import(array('file' => 'vendors' . DS . 'phpThumb' . DS . 'phpthumb.class.php', 'name' => 'MeioUpload.phpThumb', 'type' => 'file')); //mod_rewriteが使用できない場合にパスにindex.phpが入ってしまうため //絶対パスに変更 if (Configure::read('App.baseUrl')) { $name = WWW_ROOT . $name; $filename = WWW_ROOT . $filename; } $phpThumb = new phpThumb(); $phpThumb->config_allow_src_above_docroot = true; $phpThumb->setSourceFilename($name); $phpThumb->setParameter('w', $new_w); $phpThumb->setParameter('h', $new_h); $phpThumb->setParameter('zc', $zc); $parts = pathinfo($filename); //vd($parts);die(); $phpThumb->setParameter('f', $parts['extension']); if ($phpThumb->generateThumbnail()) { $phpThumb->RenderToFile($filename); } else { die($phpThumb->fatalerror); } }
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; }
$filepath = JPATH_ROOT . DS . $image; $thumbImage = JPATH_ROOT . DS . $thumb; $thumbImageLink = ''; if (false && !file_exists($thumbImage) && file_exists($filepath) && is_file($filepath)) { 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', CFG_THUMB_SERVICE_IMAGE); $phpThumb->setParameter('config_output_format', 'jpeg'); // set value to return if ($phpThumb->GenerateThumbnail()) { if (!$phpThumb->RenderToFile($thumbImage)) { // do something on failed die('Failed (size=' . $width . '):<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre>'); } $thumbImageLink = JURI::base() . $thumb; $phpThumb->purgeTempFiles(); } else { // do something with debug/error messages echo 'Failed (size=' . CFG_THUMB_SERVICE_IMAGE . ').<br>'; echo '<div style="background-color:#FFEEDD; font-weight: bold; padding: 10px;">' . $phpThumb->fatalerror . '</div>';
} } if ($ok == true) { $imageattr = @getimagesize($templocation); if ($imageattr == false) { $ok = false; $messages[] = "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[] = "The uploaded icon file was too large. ".tbl_prefix."files.must have maximum dimensions of 100x100."; require_once path . 'units/phpthumb/phpthumb.class.php'; $phpThumb = new phpThumb(); $phpThumb->setSourceFilename($templocation); $phpThumb->w = 100; $phpThumb->h = 100; $phpThumb->config_output_format = 'jpeg'; $phpThumb->config_error_die_on_error = false; if ($phpThumb->GenerateThumbnail()) { $phpThumb->RenderToFile($templocation); $imageattr[2] = "2"; } else { $ok = false; $messages[] .= 'Failed: ' . implode("\n", $phpThumb->debugmessages); } } } if ($ok == true && ($imageattr[2] > 3 || $imageattr[2] < 1)) { $message[] = "The uploaded icon file was in an image format other than JPEG, GIF or PNG. These are unsupported at present.";
private function upload($field, $baseDir, $newFileName = false, $deleteOld = false, $oldFilename = '') { $jFileInput = new JInput($_FILES); $fileInput = $jFileInput->get('jform', array(), 'array'); if (empty($fileInput)) { return false; } $field = explode('.', $field); $uploadFileName = $fileInput['name']; $uploadFileTemp = $fileInput['tmp_name']; foreach ($field as $f) { if (!empty($uploadFileName[$f]) && !empty($uploadFileTemp[$f])) { $uploadFileName = $uploadFileName[$f]; $uploadFileTemp = $uploadFileTemp[$f]; } else { $uploadFileName = ''; $uploadFileTemp = ''; break; } } if (empty($uploadFileName)) { return false; } if ($deleteOld && $oldFilename) { $oldFilename = is_array($oldFilename) ? $oldFilename : array($oldFilename); foreach ($oldFilename as $key => &$value) { $value = $baseDir . DS . $oldFilename[$key]; // $oldFilename[$key] = $value; JFile::delete($value); } } $uploadFileExt = JFile::getExt($uploadFileName); if (!is_dir($baseDir)) { if (!mkdir($baseDir, 0777, true)) { return false; } } $fileName = $newFileName ? $newFileName . '.' . $uploadFileExt : $uploadFileName; $filePath = $baseDir . DS . $fileName; $resultUpload = JFile::upload($uploadFileTemp, $filePath); if ($resultUpload) { // resize require_once JPATH_ROOT . '/jelibs/phpthumb/phpthumb.class.php'; // create phpThumb object $phpThumb = new phpThumb(); if (file_exists(JPATH_ROOT . '/jelibs/phpthumb/phpThumb.config.php') && (include_once JPATH_ROOT . '/jelibs/phpthumb/phpThumb.config.php')) { foreach ($PHPTHUMB_CONFIG as $key => $value) { $keyname = 'config_' . $key; $phpThumb->setParameter($keyname, $value); } } else { echo '<div style="color: red; border: 1px red dashed; font-weight: bold; padding: 10px; margin: 10px; display: inline-block;">Error reading ../phpThumb.config.php</div><br>'; } // this is very important when using a single object to process multiple images $phpThumb->resetObject(); // set data source $phpThumb->setSourceFilename($filePath); // set parameters (see "URL Parameters" in phpthumb.readme.txt) $phpThumb->setParameter('w', CFG_BUSINESS_LOGO_WIDTH); $phpThumb->setParameter('h', CFG_BUSINESS_LOGO_HEIGHT); $phpThumb->setParameter('zc', 'l'); // set parameters $phpThumb->setParameter('config_output_format', 'jpeg'); // generate & output thumbnail //$output_filename = 't-' . CFG_BUSINESS_LOGO_WIDTH . 'x' . CFG_BUSINESS_LOGO_HEIGHT . '-' . $fileName; $capture_raw_data = false; if ($phpThumb->GenerateThumbnail()) { $phpThumb->RenderToFile($filePath); } 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="40" cols="180" wrap="off">' . htmlentities(implode("\n* ", $phpThumb->debugmessages)) . '</textarea></form><hr>'; die; } } return $fileName; }
// only resize big image if asked require 'image_resize.php'; image_resize($source_bigimage, POPUP_IMAGE_WIDTH, POPUP_IMAGE_HEIGHT, POPUP_IMAGE_COMPRESSION); } // Start image generation include_once DIR_FS_CATALOG . 'ext/phpthumb/phpthumb.class.php'; // create phpThumb object $phpThumb = new phpThumb(); if (PRODUCT_IMAGE_WIDTH != '') { // create 2 sizes of image based on width $resized_images = array(SMALL_IMAGE_WIDTH => $root_thumbs_dir, PRODUCT_IMAGE_WIDTH => $root_products_dir); foreach ($resized_images as $resized_width => $dest_dir) { // 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($source_bigimage); $output_filename = $dest_dir . $dir . $products_image_name; // set parameters (see "URL Parameters" in phpthumb.readme.txt) $phpThumb->setParameter('config_cache_directory', $cache_dir); //doesn't work! $phpThumb->setParameter('w', $resized_width); if ($dest_dir == $root_products_dir) { if (PRODUCT_IMAGE_WIDTH == '') { $phpThumb->setParameter('h', PRODUCT_IMAGE_HEIGHT); } else { $phpThumb->setParameter('w', PRODUCT_IMAGE_WIDTH); } $phpThumb->setParameter('q', PRODUCT_IMAGE_COMPRESSION); } if ($dest_dir == $root_thumbs_dir) { if (PRODUCT_IMAGE_WIDTH == '') {
/** * This is the method that actually does the thumbnail generation by setting up * the parameters and calling phpThumb * * @return bool Success? * @author Nate Constant **/ function generateThumb($baseDir, $dir, $filename, $size, $options = array()) { // Make sure we have the name of the uploaded file and that the Model is specified if (empty($baseDir) || empty($filename)) { Debugger::log('Base directory or filename is empty'); return false; } $source = $baseDir . $dir . $filename; if (empty($size)) { $height = 100; $width = 100; } else { $height = $size['height']; $width = $size['width']; } // verify that the size is greater than 0 ( emtpy file uploaded ) if (filesize($baseDir . $dir . $filename === 0)) { Debugger::log('File is empty'); return false; } // verify that the filesystem is writable, if not add an error to the object // dont fail if not and let phpThumb try anyway $cacheDir = $baseDir . 'cache' . DS; if (!file_exists($cacheDir)) { debugger::log('Cache directory doesn\'t exist'); if (!mkdir($cacheDir)) { Debugger::log('Can\' create ' . $cacheDir); return false; } } if (!is_writable($cacheDir)) { debugger::log($cacheDir . ' not writable'); chmod($cacheDir, 0777); } // Load phpThumb App::import('Vendor', 'phpThumb', array('file' => 'phpThumb/phpthumb.class.php')); $phpThumb = new phpThumb(); // phpThumb configs $phpThumb->setParameter('config_cache_force_passthru', false); $phpThumb->setParameter('config_allow_src_above_docroot', true); // ignore aspect ratio and allow enlarging // $phpThumb->setParameter('iar', 1); // image configs $phpThumb->setSourceFilename($source); $phpThumb->setParameter('w', $width); $phpThumb->setParameter('h', $height); // auto rotate based on exif data $phpThumb->setParameter('ar', 'x'); foreach ($options as $key => $val) { $phpThumb->setParameter($key, $val); } // $phpThumb->setParameter('zc', 1); if ($phpThumb->generateThumbnail()) { if (!$phpThumb->RenderToFile($cacheDir . $filename . '-' . $height . 'x' . $width . '.jpg')) { Debugger::log('Could not render to file'); return false; } } else { Debugger::log('Could not generate thumbnail'); return false; } return true; }
// 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 // object mode does NOT pull any settings from phpThumb.config.php //$phpThumb->setParameter('config_document_root', '/home/groups/p/ph/phpthumb/htdocs/'); //$phpThumb->setParameter('config_cache_directory', '/tmp/persistent/phpthumb/cache/'); // set parameters (see "URL Parameters" in phpthumb.readme.txt) $phpThumb->setParameter('w', $thumbnail_width); //$phpThumb->setParameter('h', 100); //$phpThumb->setParameter('fltr', 'gam|1.2'); //$phpThumb->setParameter('fltr', 'wmi|../watermark.jpg|C|75|20|20'); // set options (see phpThumb.config.php)
function processEPC($photo, $dea_id) { require_once dirname(__FILE__) . "/phpThumb/phpthumb.class.php"; $errors = ''; $thumbnail_sizes = array('full' => array('h' => '600'), 'large' => array('h' => '600'), 'small' => array('w' => '200'), 'thumb1' => array('w' => '146', 'h' => '146'), 'original' => array('h' => '', 'w' => '')); $image_path_property = IMAGE_PATH_PROPERTY . $dea_id . "/"; $image_url_property = IMAGE_URL_PROPERTY . $dea_id . "/"; $attributes = getimagesize($image_path_property . $photo); foreach ($thumbnail_sizes as $ext => $dims) { if (isset($dims['w']) && $dims['w']) { $dims['w'] = $attributes[0] < $dims['w'] ? $attributes[0] : $dims['w']; } if (isset($dims['h']) && $dims['h']) { $dims['h'] = $attributes[1] < $dims['h'] ? $attributes[1] : $dims['h']; } // only process images that are big enough $phpThumb = new phpThumb(); // set data $phpThumb->setSourceFilename($image_path_property . $photo); if (isset($dims['w']) && $dims['w']) { $phpThumb->setParameter('w', $dims['w']); } if (isset($dims['h']) && $dims['h']) { $phpThumb->setParameter('h', $dims['h']); } $phpThumb->setParameter('config_output_format', 'gif'); $phpThumb->setParameter('config_allow_src_above_docroot', true); // generate & output thumbnail $output_filename = $image_path_property . str_replace('.gif', '', $photo) . '_' . $ext . '.' . $phpThumb->config_output_format; if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it! $output_size_x = ImageSX($phpThumb->gdimg_output); $output_size_y = ImageSY($phpThumb->gdimg_output); if ($output_filename) { if ($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>'; } } else { $phpThumb->OutputThumbnail(); } } else { // do something with debug/error messages $errors .= '<p>Failed (size=' . $thumbnail_width . ').<br> <div style="background-color:#FFEEDD; font-weight: bold; padding: 10px;">' . $phpThumb->fatalerror . '</div> <form><textarea rows="10" cols="60" wrap="off">' . htmlentities(implode("\n* ", $phpThumb->debugmessages)) . '</textarea></form></p><hr>'; } } if ($errors) { echo $errors; exit; } }
echo $file->getProp("type"); exit; } $file->setName("uniq"); $dest_name = $file->moveTo(IMAGE_PATH_DIRECTORY); #echo $image_path_directory.$dest_name; if (PEAR::isError($dest_name)) { echo $dest_name->getMessage(); } // create thumbnails $thumbnail_width = 100; $thumbnail_height = 100; require_once "../inx/phpThumb/phpthumb.class.php"; $phpThumb = new phpThumb(); // set data $phpThumb->setSourceFilename(IMAGE_PATH_DIRECTORY . $dest_name); $phpThumb->setParameter('h', $thumbnail_height); $phpThumb->setParameter('config_output_format', 'jpg'); // generate & output thumbnail $output_filename = IMAGE_PATH_DIRECTORY . str_replace('.jpg', '', $dest_name) . '_S.' . $phpThumb->config_output_format; if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it! $output_size_x = ImageSX($phpThumb->gdimg_output); $output_size_y = ImageSY($phpThumb->gdimg_output); if ($output_filename) { if ($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>';
// ================================================ // 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)) { $phpThumb->$key = $value; }
/** * Resize a given image */ function resizeImage($filename, $target, $params) { global $modx; if (!class_exists('phpthumb')) { include 'classes/phpthumb/phpthumb.class.php'; include 'classes/phpthumb/phpThumb.config.php'; } $phpthumb = new phpThumb(); if (!empty($PHPTHUMB_CONFIG)) { foreach ($PHPTHUMB_CONFIG as $key => $value) { $keyname = 'config_' . $key; $phpthumb->setParameter($keyname, $value); } } //Set output format as input or jpeg if not supperted $ext = strtolower(substr(strrchr($filename, '.'), 1)); if (in_array($ext, array('jpg', 'jpeg', 'png', 'gif'))) { $phpthumb->setParameter('f', $ext); } else { $phpthumb->setParameter('f', 'jpeg'); } $phpthumb->setParameter('config_document_root', rtrim($modx->config['base_path'], '/')); foreach ($params as $key => $value) { $phpthumb->setParameter($key, $value); } $phpthumb->setSourceFilename($filename); // generate & output thumbnail if ($phpthumb->GenerateThumbnail()) { $phpthumb->RenderToFile($target); } unset($phpthumb); }
////////////////////////////////////////////////////////////// // 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; if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it!
protected function makeUploadFile($fileKey, $options) { // if no file, return false if (!isset($this->FILES[$fileKey]['name']) || empty($this->FILES[$fileKey]['name'])) { return false; } if ($this->FILES[$fileKey]['error'] != 0) { $haveError = 1; $this->error[] = sprintf(lang::translate('cannot_upload_file_for_'), $this->title(isset($options['label']) ? $options['label'] : $field)); } if ($this->FILES[$fileKey]['size'] > $this->maximulFileSize * 1024) { $haveError = 1; $this->error[] = sprintf(lang::translate('the_file_is_larger_than_'), $this->title(isset($options['label']) ? $options['label'] : $field), number_format($this->maximulFileSize / 1024, 1, '.', '')); } // $this->error can be set upper, from filters or other if (isset($haveError)) { return false; } $newNameOfFile = uniqid(); if (substr($options['file']['location'], -1) != '/') { $options['file']['location'] = $options['file']['location'] . '/'; } $ext = $this->extension($this->FILES[$fileKey]['name']); $_final_newNameOfFile = $this->folder . $options['file']['location'] . $newNameOfFile . '.' . $ext; if (!is_dir($this->folder . $options['file']['location'])) { mkdir($this->folder . $options['file']['location'], 0777) or die('Error at line "' . __LINE__ . '" in method "' . __METHOD__ . '"' . (isset($this->section) ? ', section ' . $this->section : '') . '<br />Cannot create folder.'); } if (false == @copy($this->FILES[$fileKey]['tmp_name'], $_final_newNameOfFile)) { $haveError = 1; $this->error[] = sprintf(lang::translate('cannot_upload_file_for_'), $this->title(isset($options['label']) ? $options['label'] : $field)); } // stop if cannot upload if (isset($haveError)) { return false; } // if we have to resize if (empty($this->error) && isset($options['file']['resize'])) { $phpThumb = new phpThumb(); // create sizes of thumbnail $capture_raw_data = false; // set to true to insert to database rather than render to screen or file (see below) foreach ($options['file']['resize'] as $thumbnailSize => $typeOfResize) { list($_w, $_h) = explode('x', $thumbnailSize); // 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($_final_newNameOfFile); // $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 // object mode does NOT pull any settings from phpThumb.config.php # $phpThumb->setParameter('config_document_root', $this->folder); //$phpThumb->setParameter('config_cache_directory', '/tmp/persistent/phpthumb/cache/'); // make image rotate if (isset($options['file']['rotate'])) { $phpThumb->ra = (int) $options['file']['rotate']; } if (isset($options['file']['background']) && strlen($options['file']['background']) == 6) { $phpThumb->setParameter('bg', $options['file']['background']); } else { $phpThumb->setParameter('bg', 'FFFFFF'); } if (isset($options['file']['fixed-aspect']) && $typeOfResize == 'resize') { $phpThumb->setParameter('far', 'FFFFFF'); } $phpThumb->setParameter('w', $_w); $phpThumb->setParameter('h', $_h); // make crop, not resize if ($typeOfResize == 'crop') { $phpThumb->setParameter('zc', 'C'); } //$phpThumb->setParameter('fltr', 'gam|1.2'); if (isset($options['file']['watermark'])) { if (is_array($options['file']['watermark']) && isset($options['file']['watermark'][$thumbnailSize])) { $phpThumb->setParameter('fltr', 'wmi|' . $options['file']['watermark'][$thumbnailSize] . '|C|75|20|20'); } else { if (is_file($options['file']['watermark'])) { $phpThumb->setParameter('fltr', 'wmi|' . $options['file']['watermark'] . '|C|75|20|20'); } } } // set options (see phpThumb.config.php) // here you must preface each option with "config_" $phpThumb->setParameter('config_output_format', $ext); // $phpThumb->setParameter('config_imagemagick_path', '/usr/local/bin/convert'); // $phpThumb->setParameter('config_imagemagick_path', IMAGICKPATH); // $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 $folderToMove = $this->folder . $options['file']['location'] . $thumbnailSize . '/'; if (!is_dir($folderToMove)) { mkdir($folderToMove, 0777) or die('Error at line "' . __LINE__ . '" in method "' . __METHOD__ . '"' . (isset($this->section) ? ', section ' . $this->section : '') . '<br />Cannot create folder at.'); } $output_filename = $folderToMove . $newNameOfFile . '.' . $phpThumb->config_output_format; if ($phpThumb->GenerateThumbnail()) { $output_size_x = ImageSX($phpThumb->gdimg_output); $output_size_y = ImageSY($phpThumb->gdimg_output); $phpThumb->RenderToFile($output_filename); $phpThumb->purgeTempFiles(); } else { $this->error[] = sprintf(lang::translate('fail_cannot_resize_file'), $phpThumb->fatalerror, htmlentities(implode("\n* ", $phpThumb->debugmessages))); @unlink($output_filename); @unlink($_final_newNameOfFile); return false; } } // delete original file after resize if (isset($options['file']['keep-original']) && $options['file']['keep-original'] == false) { @unlink($this->folder . $options['file']['location'] . $newNameOfFile . '.' . $ext); } } return $newNameOfFile . '.' . $ext; }
/** * 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)); }
function createThumb($inFile, $outFile, $width = 0, $height = 0) { PhotoQHelper::debug('enter createThumb() ' . $this->getName()); require_once PHOTOQ_PATH . 'lib/phpThumb_1.7.9/phpthumb.class.php'; // create phpThumb object $phpThumb = new phpThumb(); //set imagemagick path here $phpThumb->config_imagemagick_path = $this->_oc->getValue('imagemagickPath') ? $this->_oc->getValue('imagemagickPath') : null; // set data source -- do this first, any settings must be made AFTER this call $phpThumb->setSourceFilename($inFile); // PLEASE NOTE: // You must set any relevant config settings here. The phpThumb // object mode does NOT pull any settings from phpThumb.config.php //$phpThumb->setParameter('config_document_root', '/home/groups/p/ph/phpthumb/htdocs/'); $phpThumb->setParameter('config_temp_directory', $this->_oc->getCacheDir()); // set parameters (see "URL Parameters" in phpthumb.readme.txt) if ($height) { $phpThumb->setParameter('h', $height); } if ($width) { $phpThumb->setParameter('w', $width); } $phpThumb->setParameter('q', $this->_quality); //rect images may be cropped to the exact size if ($this->_crop) { $phpThumb->setParameter('zc', 'C'); } //$phpThumb->setParameter('fltr', 'gam|1.2'); if ($this->_watermark && ($wmPath = get_option('wimpq_watermark'))) { $phpThumb->setParameter('fltr', 'wmi|' . $wmPath . '|' . $this->_oc->getValue('watermarkPosition') . '|' . $this->_oc->getValue('watermarkOpacity') . '|' . $this->_oc->getValue('watermarkXMargin') . '|' . $this->_oc->getValue('watermarkYMargin')); } PhotoQHelper::debug('generating thumb...'); // generate & output thumbnail //$output_filename = './thumbnails/'.basename($name.'_'.$largestSide.'.'.$phpThumb->config_output_format; if ($phpThumb->GenerateThumbnail()) { // this line is VERY important, do not remove it! PhotoQHelper::debug('generation ok'); if ($phpThumb->RenderToFile($outFile)) { PhotoQHelper::debug('rendering ok'); // do something on success return new PhotoQStatusMessage(__('Thumb created successfully', 'PhotoQ')); } else { PhotoQHelper::debug('rendering failed'); // do something with debug/error messages return new PhotoQErrorMessage(__('Failed:', 'PhotoQ') . '<pre>' . implode("\n\n", $phpThumb->debugmessages) . '</pre>'); } } else { // do something with debug/error messages return new PhotoQErrorMessage(__('Failed:', 'PhotoQ') . '<pre>' . $phpThumb->fatalerror . "\n\n" . implode("\n\n", $phpThumb->debugmessages) . '</pre>'); } }
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; } }
/** * Generate a thumbnail of an attachment * @param $file * @param $size * @return bool * @throws CException */ public function thumb($file, $size) { if (!$file) { return false; } if (file_exists($file)) { return true; } if (!file_exists(dirname($file))) { mkdir(dirname($file), 0777, true); } // find the image $image = $this->getAttachmentFile(); $defaultImage = dirname(Yii::app()->basePath) . '/data/attachment/default.jpg'; if (!$image) { if (YII_DEBUG) { throw new CException('Cannot find source image (' . $image . ').'); } $image = $defaultImage; } $fileInfo = pathinfo($image); if ($fileInfo['extension'] != 'pdf') { $imageSize = getimagesize($image); if ($imageSize[0] < $size[0]) { $size[0] = $imageSize[0]; } if ($imageSize[1] < $size[1]) { $size[1] = $imageSize[1]; } } require_once Yii::getPathOfAlias('vendor') . DIRECTORY_SEPARATOR . 'phpThumb' . DIRECTORY_SEPARATOR . 'phpThumb.php'; $phpThumb = new phpThumb(); $phpThumb->setSourceFilename($image); $phpThumb->setParameter('config_imagemagick_path', 'convert'); $phpThumb->setParameter('config_allow_src_above_docroot', 'convert'); $phpThumb->setParameter('aoe', false); $phpThumb->setParameter('w', $size[0]); $phpThumb->setParameter('h', $size[1]); $phpThumb->setParameter('f', 'JPG'); // set the output format $phpThumb->setParameter('far', 'C'); // scale outside $phpThumb->setParameter('bg', 'FFFFFF'); // scale outside if (!$phpThumb->GenerateThumbnail()) { $phpThumb->setSourceFilename($defaultImage); if (!$phpThumb->GenerateThumbnail()) { throw new CException('Cannot generate thumbnail from image (' . $image . ').'); } } if (!$phpThumb->RenderToFile($file)) { throw new CException('Cannot save thumbnail (' . $file . ').'); } return true; }
} } 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"; } else { $ok = false; $messages[] .= '#Failed: ' . implode("<br />", $phpThumb->debugmessages); unlink($um->get_new_filepath()); // it failed, so delete it. } } }
} if (@(!empty($_POST['reddit_username']))) { $l->addMember($_POST['reddit_username'], "", "reddit"); } if (@(!empty($_POST['flickr_username']))) { include_once 'includes/Page.PhotosYYY.class.php'; $p = new PhotosPage($group_name); @$p->changePersonalFlickrAccount($u->getID(), $_POST['flickr_username']); } if (isset($_FILES['avatar'])) { include_once 'includes/phpThumb/phpthumb.class.php'; include_once 'includes/custom_avatar.inc.php'; $phpThumb = new phpThumb(); $phpThumb->setParameter('config_allow_src_above_docroot', true); // very important $phpThumb->setSourceFilename($_FILES['avatar']['tmp_name']); $phpThumb->setParameter('w', 80); $phpThumb->setParameter('h', 80); $phpThumb->setParameter('zc', 1); $phpThumb->setParameter('config_output_format', 'png'); if ($phpThumb->GenerateThumbnail()) { include_once 'configs/globals.php'; $membership_id = $u->getMembershipID($group_name); $bigfile = $app_base . "avatars/{$membership_id}/80.png"; $smallfile = $app_base . "avatars/{$membership_id}/16.png"; $target = $app_base . "avatars/{$membership_id}/"; @mkdir($target); $phpThumb->RenderToFile($bigfile); makeSmallAvatar($bigfile, $smallfile); makeFlags($smallfile, $target); $u->setCustomAvatar($group_name);