本文整理汇总了PHP中phpThumb::GenerateThumbnail方法的典型用法代码示例。如果您正苦于以下问题:PHP phpThumb::GenerateThumbnail方法的具体用法?PHP phpThumb::GenerateThumbnail怎么用?PHP phpThumb::GenerateThumbnail使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类phpThumb
的用法示例。
在下文中一共展示了phpThumb::GenerateThumbnail方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: spit_phpthumb_image
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;
}
}
示例2: generateThumbnail
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;
}
示例3: thumbnail
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;
}
示例4: thumb
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);
}
}
示例5: image_resize
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;
}
示例6: phpThumb
// 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);
utility::jsAlert('Label image file successfully uploaded');
} else {
// write log
utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'bibliography', 'ERROR : ' . $_SESSION['realname'] . ' FAILED TO upload label image file ' . $image_upload->new_filename . ', with error (' . $image_upload->error . ')');
utility::jsAlert('FAILED to upload label image! Please see System Log for more detailed information');
}
示例7: makeUploadFile
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();
//.........这里部分代码省略.........
示例8: action_zip
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);
}
示例9: getPhotoFromUrl
public function getPhotoFromUrl($url, $data, $w, $h)
{
if(Yii::app()->user->isGuest)
return false;
$id_record=(int)$data['id_record'];
if(!$id_record)
return false;
$type = $data['type'];
if(!in_array($type,$this->dataTypes))
return false;
Yii::import('application.vendors.*');
require_once('/phpthumb/phpthumb.class.php');
$extention='jpg';
$id_photo = time();
$file_name = $id_photo.'.'.$extention;
$upload_path = Yii::getPathOfAlias('webroot') . Yii::app()->params['tmpFolder'].$file_name;
$PT = new phpThumb();
$PT->src = $url;
$PT->w = (int)$w;
$PT->h = (int)$h;
$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;
}
示例10: thumbnail
/**
* 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.");
}
}
}
示例11: ddCreateThumb
/**
* Делает превьюшку
*
* @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']);
}
示例12: getPhotoFromUrl
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;
}
}
示例13: uploadImages
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;
}
示例14: file_cache_save_thumbnail_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;
}
}
示例15: resizeImage
/**
* 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);
}