本文整理汇总了PHP中JImage::loadFile方法的典型用法代码示例。如果您正苦于以下问题:PHP JImage::loadFile方法的具体用法?PHP JImage::loadFile怎么用?PHP JImage::loadFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JImage
的用法示例。
在下文中一共展示了JImage::loadFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setup
/**
* Method to attach a JForm object to the field.
* Catch upload files when form setup.
*
* @param object &$element The JXmlElement object representing the <field /> tag for the form field object.
* @param mixed $value The form field value to validate.
* @param string $group The field name group control value. This acts as as an array container for the field.
* For example if the field has name="foo" and the group value is set to "bar" then the
* full field name would end up being "bar[foo]".
*
* @return boolean True on success.
*/
public function setup(SimpleXMLElement $element, $value, $group = null)
{
parent::setup($element, $value, $group);
if (JRequest::getVar($this->element['name'] . '_delete') == 1) {
$this->value = '';
} else {
// Upload Image
// ===============================================
if (isset($_FILES['jform']['name']['profile'])) {
foreach ($_FILES['jform']['name']['profile'] as $key => $var) {
if (!$var) {
continue;
}
// Get Field Attr
$width = $this->element['save_width'] ? $this->element['save_width'] : 800;
$height = $this->element['save_height'] ? $this->element['save_height'] : 800;
// Build File name
$src = $_FILES['jform']['tmp_name']['profile'][$key];
$var = explode('.', $var);
$date = JFactory::getDate('now', JFactory::getConfig()->get('offset'));
$name = md5((string) $date . $width . $height . $src) . '.' . array_pop($var);
$url = "images/cck/{$date->year}/{$date->month}/{$date->day}/" . $name;
// A Event for extend.
JFactory::getApplication()->triggerEvent('onCCKEngineUploadImage', array(&$url, &$this, &$this->element));
$dest = JPATH_ROOT . '/' . $url;
// Upload First
JFile::upload($src, $dest);
// Resize image
$img = new JImage();
$img->loadFile(JPATH_ROOT . '/' . $url);
$img = $img->resize($width, $height);
switch (array_pop($var)) {
case 'gif':
$type = IMAGETYPE_GIF;
break;
case 'png':
$type = IMAGETYPE_PNG;
break;
default:
$type = IMAGETYPE_JPEG;
break;
}
// save
$img->toFile($dest, $type, array('quality' => 85));
// Set in Value
$this->value = $url;
}
}
}
return true;
}
示例2: resize
/**
* Resize an image, auto catch it from remote host and generate a new thumb in cache dir.
*
* @param string $url Image URL, recommend a absolute URL.
* @param integer $width Image width, do not include 'px'.
* @param integer $height Image height, do not include 'px'.
* @param boolean $zc Crop or not.
* @param integer $q Image quality
* @param string $file_type File type.
*
* @return string The cached thumb URL.
*/
public static function resize($url = null, $width = 100, $height = 100, $zc = 0, $q = 85, $file_type = 'jpg')
{
if (!$url) {
return self::getDefaultImage($width, $height, $zc, $q, $file_type);
}
$path = self::getImagePath($url);
try {
$img = new JImage();
if (JFile::exists($path)) {
$img->loadFile($path);
} else {
return self::getDefaultImage($width, $height, $zc, $q, $file_type);
}
// get Width Height
$imgdata = JImage::getImageFileProperties($path);
// set save data
if ($file_type != 'png' && $file_type != 'gif') {
$file_type = 'jpg';
}
$file_name = md5($url . $width . $height . $zc . $q . implode('', (array) $imgdata)) . '.' . $file_type;
$file_path = self::$cache_path . DS . $file_name;
$file_url = trim(self::$cache_url, '/') . '/' . $file_name;
// img exists?
if (JFile::exists($file_path)) {
return $file_url;
}
// crop
if ($zc) {
$img = self::crop($img, $width, $height, $imgdata);
}
// resize
$img = $img->resize($width, $height);
// save
switch ($file_type) {
case 'gif':
$type = IMAGETYPE_GIF;
break;
case 'png':
$type = IMAGETYPE_PNG;
break;
default:
$type = IMAGETYPE_JPEG;
break;
}
JFolder::create(self::$cache_path);
$img->toFile($file_path, $type, array('quality' => $q));
return $file_url;
} catch (Exception $e) {
if (JDEBUG) {
echo $e->getMessage();
}
return self::getDefaultImage($width, $height, $zc, $q, $file_type);
}
}
示例3: _resize
//.........这里部分代码省略.........
list($orig_w, $orig_h) = getimagesize($absoluteImagePath);
if (isset($opts['w'])) {
if (stripos($opts['w'], '%') !== false) {
$w = (int) ((double) str_replace('%', '', $opts['w']) / 100 * $orig_w);
} else {
$w = (int) $opts['w'];
}
}
if (isset($opts['h'])) {
if (stripos($opts['h'], '%') !== false) {
$h = (int) ((double) str_replace('%', '', $opts['h']) / 100 * $orig_h);
} else {
$h = (int) $opts['h'];
}
}
if (!isset($opts['w']) && !isset($opts['h'])) {
list($w, $h) = array($orig_w, $orig_h);
}
//$filename = md5_file($absoluteImagePath);
//$imageExt = JFile::getExt($absoluteImagePaths);
$imageName = preg_replace('/\\.' . $ext . '$/', '', JFile::getName($absoluteImagePath));
$imageNameNew = $imageName . '_w' . $w . 'xh' . $h;
if (!empty($w) and !empty($h)) {
$imageNameNew = $imageName . '_w' . $w . '_h' . $h . (isset($opts['crop']) && $opts['crop'] == true ? "_cp" : "") . (isset($opts['scale']) && $opts['scale'] == true ? "_sc" : "") . '_q' . $opts['quality'];
} elseif (!empty($w)) {
$imageNameNew = $imageName . '_w' . $w . '_q' . $opts['quality'];
} elseif (!empty($h)) {
$imageNameNew = $imageName . '_h' . $h . '_q' . $opts['quality'];
} else {
return false;
}
//$absoluteImagePathNew = str_replace($imageName.'.'.$ext, $imageNameNew.'.'.$ext, $absoluteImagePath);//JPath::clean(JPATH_ROOT.'/'.$relativePathNew);
$absoluteImagePathNew = JPath::clean(JPATH_ROOT . '/' . $cacheFolder . $imageNameNew . '.' . $ext);
$relativeImagePathNew = preg_replace('/\\\\/', '/', str_replace(JPATH_ROOT, "", $absoluteImagePathNew));
if (JFile::exists($absoluteImagePathNew)) {
$imageDateOrigin = filemtime($absoluteImagePath);
$imageDateThumb = filemtime($absoluteImagePathNew);
$clearCache = $imageDateOrigin > $imageDateThumb;
if ($clearCache == false) {
return $relativeImagePathNew;
}
}
//echo $relativeImagePathNew;die;
if ($this->imagick_process == 'jimage' && class_exists('JImage')) {
// s2s Use Joomla JImage class (GD)
if (empty($w)) {
$w = 0;
}
if (empty($h)) {
$h = 0;
}
//echo $imagePath;die;
// Keep proportions if w or h is not defined
list($width, $height) = getimagesize($absoluteImagePath);
//echo $width.' '.$height;die;
if (!$w) {
$w = $h / $height * $width;
}
if (!$h) {
$h = $w / $width * $height;
}
//echo $imagePath;die;
//echo (JURI::root().$imagePath);die;
// http://stackoverflow.com/questions/10842734/how-resize-image-in-joomla
try {
$image = new JImage();
$image->loadFile($absoluteImagePath);
//echo'<pre>';var_dump($image);die;
} catch (Exception $e) {
return str_replace(JPATH_ROOT, "", $absoluteImagePath);
// "Attempting to load an image of unsupported type: image/x-ms-bmp"
}
if ($opts['crop'] === true) {
$rw = $w;
$rh = $h;
if ($width / $height < $rw / $rh) {
$rw = $w;
$rh = $rw / $width * $height;
} else {
$rh = $h;
$rw = $rh / $height * $width;
}
$resizedImage = $image->resize($rw, $rh)->crop($w, $h);
} else {
$resizedImage = $image->resize($w, $h);
}
$properties = JImage::getImageFileProperties($absoluteImagePath);
// fix compression level must be 0 through 9 (in case of png)
$quality = $opts['quality'];
if ($properties->type == IMAGETYPE_PNG) {
$quality = round(9 - $quality * 9 / 100);
// 100 quality = 0 compression, 0 quality = 9 compression
}
//echo '<pre>';var_dump($properties);die;
$resizedImage->toFile($absoluteImagePathNew, $properties->type, array('quality' => $quality));
}
//echo $relativeImagePathNew;die;
# return cache file path
return $relativeImagePathNew;
}
示例4: jimport
function upload_image()
{
$user = JFactory::getUser();
JFactory::getDocument()->setMimeEncoding('application/json');
if ($user->guest) {
echo json_encode(array('error' => 'no permissions'));
return JFactory::getApplication()->close();
}
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
$file = JRequest::getVar('Filedata', '', 'files', 'array');
$extension = JRequest::getVar('extension', null);
//mime_content_type()
if (($imginfo = getimagesize($file['tmp_name'])) === false) {
echo json_encode(array('error' => 'not an image'));
return JFactory::getApplication()->close();
}
$params = JComponentHelper::getParams('com_media');
$allowed_mime = explode(',', $params->get('upload_mime'));
$illegal_mime = explode(',', $params->get('upload_mime_illegal'));
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$type = finfo_file($finfo, $file['tmp_name']);
if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) {
echo json_encode(array('error' => 'dont try to fuck the server'));
return JFactory::getApplication()->close();
}
finfo_close($finfo);
} elseif (function_exists('mime_content_type')) {
$type = mime_content_type($file['tmp_name']);
if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) {
echo json_encode(array('error' => 'COM_KSM_ERROR_WARNINVALID_MIME'));
return JFactory::getApplication()->close();
}
} elseif (!$user->authorise('core.manage')) {
echo json_encode(array('error' => 'COM_KSM_ERROR_WARNNOTADMIN'));
return JFactory::getApplication()->close();
}
$to = JRequest::getString('to', '');
$folder = JRequest::getString('folder', '');
$path = JPATH_ROOT;
$to = explode("/", $to);
foreach ($to as $s) {
$path = $path . DS . $s;
if (!JFolder::exists($path)) {
if (!JFolder::create($path)) {
echo json_encode(array('error' => 'COM_KSM_ERROR_CREATEDIR'));
return JFactory::getApplication()->close();
}
}
}
try {
$imageObject = new JImage();
$imageObject->loadFile($file['tmp_name']);
} catch (Exception $e) {
echo json_encode(array('error' => $e->getMessage()));
return JFactory::getApplication()->close();
}
$pathinfo = pathinfo($file['name']);
$fileName = $path . DS . microtime(true) . '.' . $pathinfo['extension'];
try {
$imageObject->toFile($fileName, IMAGETYPE_JPEG, array('quality', 100));
//$imageObject->save($fileName, 100);
} catch (Exception $e) {
echo json_encode(array('error' => $e->getMessage()));
return JFactory::getApplication()->close();
}
$url = KSMedia::resizeImage(basename($fileName), $folder, null, null, null, $extension);
$model = $this->getModel('media');
$model->form = 'images';
$item = new stdClass();
$table = $model->getTable('Files');
$table->media_type = 'images';
$table->filename = str_replace(JPATH_ROOT, '', $fileName);
$table->folder = $folder;
$table->id = '{id}';
$item->images = array(0 => $table);
$form = $model->getForm();
$form->setFieldAttribute('images', 'extension', $extension);
$form->bind($item);
$html = $form->getInput('images');
echo json_encode(array('error' => '', 'filename' => str_replace(JPATH_ROOT, '', $fileName), 'url' => $url, 'html' => $html));
JFactory::getApplication()->close();
}
示例5: createThumb
public static function createThumb($path, $width = 100, $height = 100, $crop = 2, $cachefolder = 'hgimages', $external = 0)
{
$myImage = new JImage();
if (!$external) {
$myImage->loadFile(JPATH_SITE . DS . $path);
} else {
$myImage->loadFile($path);
}
if ($myImage->isLoaded()) {
// $filename = end(explode('/', $path));
$filename = JFile::getName($path);
$filefolder = substr(md5(self::getFolderPath($path)), 1, 10);
$newfilename = $width . 'x' . $height . 'x' . $crop . '_' . $filefolder . '_' . JFile::makeSafe($filename);
$hgimages = JPATH_CACHE . '/' . $cachefolder . '/';
if (!JFolder::exists($hgimages)) {
JFolder::create($hgimages);
}
$fileExists = JFile::exists($hgimages . $newfilename);
if (!$fileExists) {
switch ($crop) {
// Case for self::CROP
case 4:
$resizedImage = $myImage->crop($width, $height, null, null, true);
break;
// Case for self::CROP_RESIZE
// Case for self::CROP_RESIZE
case 5:
$resizedImage = $myImage->cropResize($width, $height, true);
break;
default:
$resizedImage = $myImage->resize($width, $height, true, $crop);
break;
}
$properties = $myImage->getImageFileProperties($path);
$mime = $properties->mime;
if ($mime == 'image/jpeg') {
$type = IMAGETYPE_JPEG;
} elseif ($mime = 'image/png') {
$type = IMAGETYPE_PNG;
} elseif ($mime = 'image/gif') {
$type = IMAGETYPE_GIF;
}
$resizedImage->toFile($hgimages . $newfilename, $type);
}
return $newfilename;
} else {
return "My file is not loaded";
}
}
示例6: createThumb
public static function createThumb($path, $width = 100, $height = 100, $crop = 2)
{
$myImage = new JImage();
$myImage->loadFile(JPATH_SITE . DS . $path);
if ($myImage->isLoaded()) {
// $filename = end(explode('/', $path));
$filename = JFile::getName($path);
$filefolder = substr(md5(self::getFolderPath($path)), 1, 10);
$newfilename = $width . 'x' . $height . '_' . $filefolder . '_' . JFile::makeSafe($filename);
$fileExists = JFile::exists(JPATH_CACHE . '/' . $newfilename);
if (!$fileExists) {
$resizedImage = $myImage->resize($width, $height, true, $crop);
$properties = $myImage->getImageFileProperties($path);
$mime = $properties->mime;
if ($mime == 'image/jpeg') {
$type = IMAGETYPE_JPEG;
} elseif ($mime = 'image/png') {
$type = IMAGETYPE_PNG;
} elseif ($mime = 'image/gif') {
$type = IMAGETYPE_GIF;
}
$resizedImage->toFile(JPATH_CACHE . '/' . $newfilename, $type);
}
return $newfilename;
} else {
return "My file is not loaded";
}
}
示例7: createThumbnail
/**
* Create a thumbnail from an image file.
*
* <code>
* $myFile = "/tmp/myfile.jpg";
*
* $options = array(
* "destination" => "image/mypic.jpg",
* "width" => 200,
* "height" => 200,
* "scale" => JImage::SCALE_INSIDE
* );
*
* $file = new PrismFileImage($myFile);
* $file->createThumbnail($options);
*
* </code>
*
* @param array $options Some options used in the process of generating thumbnail.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*
* @return string A location to the new file.
*/
public function createThumbnail($options)
{
$width = ArrayHelper::getValue($options, "width", 100);
$height = ArrayHelper::getValue($options, "height", 100);
$scale = ArrayHelper::getValue($options, "scale", \JImage::SCALE_INSIDE);
$destination = ArrayHelper::getValue($options, "destination");
if (!$destination) {
throw new \InvalidArgumentException(\JText::_("LIB_PRISM_ERROR_INVALID_FILE_DESTINATION"));
}
// Generate thumbnail.
$image = new \JImage();
$image->loadFile($this->file);
if (!$image->isLoaded()) {
throw new \RuntimeException(\JText::sprintf('LIB_PRISM_ERROR_FILE_NOT_FOUND', $this->file));
}
// Resize the file as a new object
$thumb = $image->resize($width, $height, true, $scale);
$fileName = basename($this->file);
$ext = \JString::strtolower(\JFile::getExt(\JFile::makeSafe($fileName)));
switch ($ext) {
case "gif":
$type = IMAGETYPE_GIF;
break;
case "png":
$type = IMAGETYPE_PNG;
break;
case IMAGETYPE_JPEG:
default:
$type = IMAGETYPE_JPEG;
}
$thumb->toFile($destination, $type);
return $destination;
}
示例8: resize
/**
* Resize an image, auto catch it from remote host and generate a new thumb in cache dir.
*
* @param string $url Image URL, recommend a absolute URL.
* @param integer $width Image width, do not include 'px'.
* @param integer $height Image height, do not include 'px'.
* @param int $method Crop or not.
* @param integer $q Image quality
* @param string $file_type File type.
*
* @return string The cached thumb URL.
*/
public function resize($url = null, $width = 100, $height = 100, $method = \JImage::SCALE_INSIDE, $q = 85, $file_type = 'jpg')
{
if (!$url) {
return $this->getDefaultImage($width, $height, $method, $q, $file_type);
}
$path = $this->getImagePath($url);
try {
$img = new \JImage();
if (\JFile::exists($path)) {
$img->loadFile($path);
} else {
return $this->getDefaultImage($width, $height, $method, $q, $file_type);
}
// If file type not png or gif, use jpg as default.
if ($file_type != 'png' && $file_type != 'gif') {
$file_type = 'jpg';
}
// Using md5 hash
$handler = $this->hashHandler;
$file_name = $handler($url . $width . $height . $method . $q) . '.' . $file_type;
$file_path = $this->config['path.cache'] . '/' . $file_name;
$file_url = trim($this->config['url.cache'], '/') . '/' . $file_name;
// Img exists?
if (\JFile::exists($file_path)) {
return $file_url;
}
// Crop
if ($method === true) {
$method = \JImage::CROP_RESIZE;
} elseif ($method === false) {
$method = \JImage::SCALE_INSIDE;
}
$img = $img->generateThumbs($width . 'x' . $height, $method);
// Save
switch ($file_type) {
case 'gif':
$type = IMAGETYPE_GIF;
break;
case 'png':
$type = IMAGETYPE_PNG;
break;
default:
$type = IMAGETYPE_JPEG;
break;
}
// Create folder
if (!is_dir(dirname($file_path))) {
\JFolder::create(dirname($file_path));
}
$img[0]->toFile($file_path, $type, array('quality' => $q));
return $file_url;
} catch (\Exception $e) {
if (JDEBUG) {
echo $e->getMessage();
}
return $this->getDefaultImage($width, $height, $method, $q, $file_type);
}
}
示例9: getProportion
public static function getProportion($path)
{
$myImage = new JImage();
$imgPath = JPATH_SITE . DS . $path;
$myImage->loadFile($imgPath);
if ($myImage->isLoaded()) {
$properties = $myImage->getImageFileProperties($imgPath);
return $properties->height / $properties->width * 100;
} else {
return;
}
}
示例10: onContentAfterSave
/**
* Plugin that manipulate uploaded images
*
* @param string $context The context of the content being passed to the plugin.
* @param object &$object_file The file object.
*
* @return object The file object.
*/
public function onContentAfterSave($context, &$object_file)
{
// Are we in the right context?
if ($context != 'com_media.file') {
return;
}
$file = pathinfo($object_file->filepath);
// Skip if the pass through keyword is set
if (preg_match('/' . $this->params->get('passthrough') . '_/', $file['filename'])) {
return;
}
$image = new JImage();
// Load the file
$image->loadFile($object_file->filepath);
// Get the properties
$properties = $image->getImageFileProperties($object_file->filepath);
// Skip if the width is less or equal to the required
if ($properties->width <= $this->params->get('maxwidth')) {
return;
}
// Get the image type
if (preg_match('/jp(e)g/', mb_strtolower($properties->mime))) {
$imageType = 'IMAGETYPE_JPEG';
}
if (preg_match('/gif/', mb_strtolower($properties->mime))) {
$imageType = 'IMAGETYPE_GIF';
}
if (preg_match('/png/', mb_strtolower($properties->mime))) {
$imageType = 'IMAGETYPE_PNG';
}
// Resize the image
$image->resize($this->params->get('maxwidth'), '', false);
// Overwrite the file
$image->toFile($object_file->filepath, $imageType, array('quality' => $this->params->get('quality')));
return $object_file;
}
示例11: uploadPitchImage
/**
* Upload a pitch image.
*
* @param array $image
*
* @throws Exception
*
* @return array
*/
public function uploadPitchImage($image)
{
$app = JFactory::getApplication();
/** @var $app JApplicationSite */
$uploadedFile = JArrayHelper::getValue($image, 'tmp_name');
$uploadedName = JArrayHelper::getValue($image, 'name');
$errorCode = JArrayHelper::getValue($image, 'error');
// Load parameters.
$params = JComponentHelper::getParams($this->option);
/** @var $params Joomla\Registry\Registry */
$destFolder = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $params->get("images_directory", "images/crowdfunding"));
$tmpFolder = $app->get("tmp_path");
// Joomla! media extension parameters
$mediaParams = JComponentHelper::getParams("com_media");
/** @var $mediaParams Joomla\Registry\Registry */
jimport("itprism.file");
jimport("itprism.file.uploader.local");
jimport("itprism.file.validator.size");
jimport("itprism.file.validator.image");
jimport("itprism.file.validator.server");
$file = new ITPrismFile();
// Prepare size validator.
$KB = 1024 * 1024;
$fileSize = (int) $app->input->server->get('CONTENT_LENGTH');
$uploadMaxSize = $mediaParams->get("upload_maxsize") * $KB;
$sizeValidator = new ITPrismFileValidatorSize($fileSize, $uploadMaxSize);
// Prepare server validator.
$serverValidator = new ITPrismFileValidatorServer($errorCode, array(UPLOAD_ERR_NO_FILE));
// Prepare image validator.
$imageValidator = new ITPrismFileValidatorImage($uploadedFile, $uploadedName);
// Get allowed mime types from media manager options
$mimeTypes = explode(",", $mediaParams->get("upload_mime"));
$imageValidator->setMimeTypes($mimeTypes);
// Get allowed image extensions from media manager options
$imageExtensions = explode(",", $mediaParams->get("image_extensions"));
$imageValidator->setImageExtensions($imageExtensions);
$file->addValidator($sizeValidator)->addValidator($imageValidator)->addValidator($serverValidator);
// Validate the file
if (!$file->isValid()) {
throw new RuntimeException($file->getError());
}
// Generate temporary file name
$ext = JString::strtolower(JFile::makeSafe(JFile::getExt($image['name'])));
jimport("itprism.string");
$generatedName = new ITPrismString();
$generatedName->generateRandomString(32);
$tmpDestFile = $tmpFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext;
// Prepare uploader object.
$uploader = new ITPrismFileUploaderLocal($uploadedFile);
$uploader->setDestination($tmpDestFile);
// Upload temporary file
$file->setUploader($uploader);
$file->upload();
// Get file
$tmpDestFile = $file->getFile();
if (!is_file($tmpDestFile)) {
throw new Exception('COM_CROWDFUNDING_ERROR_FILE_CANT_BE_UPLOADED');
}
// Resize image
$image = new JImage();
$image->loadFile($tmpDestFile);
if (!$image->isLoaded()) {
throw new Exception(JText::sprintf('COM_CROWDFUNDING_ERROR_FILE_NOT_FOUND', $tmpDestFile));
}
$imageName = $generatedName . "_pimage.png";
$imageFile = JPath::clean($destFolder . DIRECTORY_SEPARATOR . $imageName);
// Create main image
$width = $params->get("pitch_image_width", 600);
$height = $params->get("pitch_image_height", 400);
$image->resize($width, $height, false);
$image->toFile($imageFile, IMAGETYPE_PNG);
// Remove the temporary
if (is_file($tmpDestFile)) {
JFile::delete($tmpDestFile);
}
return $imageName;
}
示例12: uploadImage
/**
* Upload an image
*
* @param array $image Array with information about uploaded file.
*
* @throws RuntimeException
* @return array
*/
public function uploadImage($image)
{
$app = JFactory::getApplication();
/** @var $app JApplicationAdministrator */
$uploadedFile = Joomla\Utilities\ArrayHelper::getValue($image, 'tmp_name');
$uploadedName = Joomla\Utilities\ArrayHelper::getValue($image, 'name');
$errorCode = Joomla\Utilities\ArrayHelper::getValue($image, 'error');
$tmpFolder = $app->get("tmp_path");
/** @var $params Joomla\Registry\Registry */
$params = JComponentHelper::getParams($this->option);
$destFolder = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $params->get("images_directory", "/images/profiles"));
$options = array("width" => $params->get("image_width"), "height" => $params->get("image_height"), "small_width" => $params->get("image_small_width"), "small_height" => $params->get("image_small_height"), "square_width" => $params->get("image_square_width"), "square_height" => $params->get("image_square_height"), "icon_width" => $params->get("image_icon_width"), "icon_height" => $params->get("image_icon_height"));
// Joomla! media extension parameters
/** @var $mediaParams Joomla\Registry\Registry */
$mediaParams = JComponentHelper::getParams("com_media");
jimport("itprism.file");
jimport("itprism.file.uploader.local");
jimport("itprism.file.validator.size");
jimport("itprism.file.validator.image");
jimport("itprism.file.validator.server");
$file = new Prism\File\File();
// Prepare size validator.
$KB = 1024 * 1024;
$fileSize = (int) $app->input->server->get('CONTENT_LENGTH');
$uploadMaxSize = $mediaParams->get("upload_maxsize") * $KB;
// Prepare file size validator
$sizeValidator = new Prism\File\Validator\Size($fileSize, $uploadMaxSize);
// Prepare server validator.
$serverValidator = new Prism\File\Validator\Server($errorCode, array(UPLOAD_ERR_NO_FILE));
// Prepare image validator.
$imageValidator = new Prism\File\Validator\Image($uploadedFile, $uploadedName);
// Get allowed mime types from media manager options
$mimeTypes = explode(",", $mediaParams->get("upload_mime"));
$imageValidator->setMimeTypes($mimeTypes);
// Get allowed image extensions from media manager options
$imageExtensions = explode(",", $mediaParams->get("image_extensions"));
$imageValidator->setImageExtensions($imageExtensions);
$file->addValidator($sizeValidator)->addValidator($imageValidator)->addValidator($serverValidator);
// Validate the file
if (!$file->isValid()) {
throw new RuntimeException($file->getError());
}
// Generate temporary file name
$ext = JFile::makeSafe(JFile::getExt($image['name']));
$generatedName = new Prism\String();
$generatedName->generateRandomString(32);
$tmpDestFile = $tmpFolder . DIRECTORY_SEPARATOR . $generatedName . "." . $ext;
// Prepare uploader object.
$uploader = new Prism\File\Uploader\Local($uploadedFile);
$uploader->setDestination($tmpDestFile);
// Upload temporary file
$file->setUploader($uploader);
$file->upload();
// Get file
$tmpSourceFile = $file->getFile();
if (!is_file($tmpSourceFile)) {
throw new RuntimeException('COM_SOCIALCOMMUNITY_ERROR_FILE_CANT_BE_UPLOADED');
}
// Generate file names for the image files.
$generatedName->generateRandomString(32);
$imageName = $generatedName . "_image.png";
$smallName = $generatedName . "_small.png";
$squareName = $generatedName . "_square.png";
$iconName = $generatedName . "_icon.png";
// Resize image
$image = new JImage();
$image->loadFile($tmpSourceFile);
if (!$image->isLoaded()) {
throw new RuntimeException(JText::sprintf('COM_SOCIALCOMMUNITY_ERROR_FILE_NOT_FOUND', $tmpSourceFile));
}
$imageFile = $destFolder . DIRECTORY_SEPARATOR . $imageName;
$smallFile = $destFolder . DIRECTORY_SEPARATOR . $smallName;
$squareFile = $destFolder . DIRECTORY_SEPARATOR . $squareName;
$iconFile = $destFolder . DIRECTORY_SEPARATOR . $iconName;
// Create profile picture
$width = Joomla\Utilities\ArrayHelper::getValue($options, "image_width", 200);
$height = Joomla\Utilities\ArrayHelper::getValue($options, "image_height", 200);
$image->resize($width, $height, false);
$image->toFile($imageFile, IMAGETYPE_PNG);
// Create small profile picture
$width = Joomla\Utilities\ArrayHelper::getValue($options, "small_width", 100);
$height = Joomla\Utilities\ArrayHelper::getValue($options, "small_height", 100);
$image->resize($width, $height, false);
$image->toFile($smallFile, IMAGETYPE_PNG);
// Create square picture
$width = Joomla\Utilities\ArrayHelper::getValue($options, "square_width", 50);
$height = Joomla\Utilities\ArrayHelper::getValue($options, "square_height", 50);
$image->resize($width, $height, false);
$image->toFile($squareFile, IMAGETYPE_PNG);
// Create icon picture
$width = Joomla\Utilities\ArrayHelper::getValue($options, "icon_width", 24);
$height = Joomla\Utilities\ArrayHelper::getValue($options, "icon_height", 24);
//.........这里部分代码省略.........
示例13: uploadImages
function uploadImages($file, $currentImage = null)
{
if ($file) {
$maxSize = 2 * 1024 * 1024;
$arr = array('image/jpeg', 'image/jpg', 'image/bmp', 'image/gif', 'image/png', 'image/ico');
// Create folder
$tzFolder = 'tz_portfolio';
$tzUserFolder = 'users';
$tzFolderPath = JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . $tzFolder;
$tzUserFolderPath = $tzFolderPath . DIRECTORY_SEPARATOR . $tzUserFolder;
if (!JFolder::exists($tzFolderPath)) {
JFolder::create($tzFolderPath);
if (!JFile::exists($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
JFile::write($tzFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
}
}
if (JFolder::exists($tzFolderPath)) {
if (!JFolder::exists($tzUserFolderPath)) {
JFolder::create($tzUserFolderPath);
if (!JFile::exists($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html')) {
JFile::write($tzUserFolderPath . DIRECTORY_SEPARATOR . 'index.html', htmlspecialchars_decode('<!DOCTYPE html><title></title>'));
}
}
}
if (is_array($file)) {
foreach ($file as $key => $val) {
if (is_array($val)) {
foreach ($val as $key2 => $val2) {
$file[$key] = $val2;
}
}
}
//Upload image
if (in_array($file['type'], $arr)) {
if ($file['size'] <= $maxSize) {
$desFileName = 'user_' . time() . uniqid() . '.' . JFile::getExt($file['name']);
$desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
if (JFile::exists($file['tmp_name'])) {
if (!JFile::copy($file['tmp_name'], $desPath)) {
JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_CAN_NOT_UPLOAD_FILE'));
}
$image = new JImage();
$image->loadFile($desPath);
$params = JComponentHelper::getParams('com_tz_portfolio');
if ($params->get('tz_user_image_width', 100)) {
$width = $params->get('tz_user_image_width', 100);
}
$height = ceil($image->getHeight() * $width / $image->getWidth());
$image = $image->resize($width, $height);
$type = $this->_getImageType($file['name']);
$image->toFile($desPath, $type);
$this->deleteImages($currentImage);
return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
}
} else {
JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_SIZE_TOO_LARGE'));
}
} else {
JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_FILE_NOT_SUPPORTED'));
}
} else {
tzportfolioimport('HTTPFetcher');
tzportfolioimport('readfile');
$image = new Services_Yadis_PlainHTTPFetcher();
$image = $image->get($file);
if (in_array($image->headers['Content-Type'], $arr)) {
if ($image->headers['Content-Length'] > $maxSize) {
$this->deleteImages($currentImage);
$desFileName = 'user_' . time() . uniqid() . '.' . str_replace('image/', '', $image->headers['Content-Type']);
$desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
if (JFolder::exists($tzFolderPath)) {
if (!JFile::write($desPath, $image->body)) {
$this->setError(JText::_('COM_TZ_PORTFOLIO_CAN_NOT_UPLOAD_FILE'));
return false;
}
return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
}
} else {
JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_SIZE_TOO_LARGE'));
}
} else {
JError::raiseNotice(300, JText::_('COM_TZ_PORTFOLIO_IMAGE_FILE_NOT_SUPPORTED'));
}
}
}
if ($currentImage) {
return $currentImage;
}
return '';
}
示例14: setup
/**
* Method to attach a JForm object to the field.
* Catch upload files when form setup.
*
* @param SimpleXMLElement $element The JXmlElement object representing the <field /> tag for the form field object.
* @param mixed $value The form field value to validate.
* @param string $group The field name group control value. This acts as as an array container for the field.
* For example if the field has name="foo" and the group value is set to "bar" then the
* full field name would end up being "bar[foo]".
*
* @return boolean True on success.
*/
public function setup(SimpleXMLElement $element, $value, $group = null)
{
parent::setup($element, $value, $group);
$container = \Windwalker\DI\Container::getInstance();
$input = $container->get('input');
$delete = isset($_REQUEST['jform']['profile'][$this->element['name'] . '_delete']) ? $_REQUEST['jform']['profile'][$this->element['name'] . '_delete'] : 0;
if ($delete == 1) {
$this->value = '';
} else {
// Upload Image
// ===============================================
if (isset($_FILES['jform']['name']['profile'])) {
foreach ($_FILES['jform']['name']['profile'] as $key => $var) {
if (!$var) {
continue;
}
// Get Field Attr
$width = $this->element['save_width'] ? $this->element['save_width'] : 800;
$height = $this->element['save_height'] ? $this->element['save_height'] : 800;
// Build File name
$src = $_FILES['jform']['tmp_name']['profile'][$key];
$var = explode('.', $var);
$date = DateHelper::getDate();
$name = md5((string) $date . $width . $height . $src) . '.' . array_pop($var);
$url = "images/cck/{$date->year}/{$date->month}/{$date->day}/" . $name;
// A Event for extend.
$container->get('event.dispatcher')->trigger('onCCKEngineUploadImage', array(&$url, &$this, &$this->element));
$dest = JPATH_ROOT . '/' . $url;
// Upload First
JFile::upload($src, $dest);
// Resize image
$img = new JImage();
$img->loadFile(JPATH_ROOT . '/' . $url);
$img = $img->resize($width, $height);
switch (array_pop($var)) {
case 'gif':
$type = IMAGETYPE_GIF;
break;
case 'png':
$type = IMAGETYPE_PNG;
break;
default:
$type = IMAGETYPE_JPEG;
break;
}
// Save
$img->toFile($dest, $type, array('quality' => 85));
// Set in Value
$this->value = $url;
// Clean cache
$thumb = $this->getThumbPath();
if (is_file(JPATH_ROOT . '/' . $thumb)) {
\JFile::delete(JPATH_ROOT . '/' . $thumb);
}
}
}
}
return true;
}
示例15: save
//.........这里部分代码省略.........
}
}
}
$path = '';
$path_hover = '';
jimport('joomla.filesystem.file');
$imageType = null;
$imageMimeType = null;
$imageSize = null;
$image_hoverType = null;
$image_hoverMimeType = null;
$image_hoverSize = null;
// Create original image with new name (upload from client)
if (count($images) && !empty($images['tmp_name'])) {
// Get image file type
$imageType = JFile::getExt($images['name']);
$imageType = strtolower($imageType);
// Get image's mime type
$imageMimeType = $images['type'];
// Get image's size
$imageSize = $images['size'];
$path = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR;
$path .= $data->alias . '-' . $data->id . '_o';
$path .= '.' . JFile::getExt($images['name']);
if ($input->getCmd('task') == 'save2copy' && $input->getInt('id')) {
$image_data['url_server'] = null;
}
} elseif (isset($image_data['url_server']) && !empty($image_data['url_server'])) {
// Create original image with new name (upload from server)
// Get image file type
$imageType = JFile::getExt($image_data['url_server']);
$imageType = strtolower($imageType);
// Get image's mime type
$imageObj->loadFile(JPATH_ROOT . DIRECTORY_SEPARATOR . $image_data['url_server']);
$imageMimeType = $imageObj->getImageFileProperties($imageObj->getPath());
$imageMimeType = $imageMimeType->mime;
// Get image's size
$imageSize = $imageMimeType->filesize;
$path = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR;
$path .= $data->alias . '-' . $data->id . '_o';
$path .= '.' . JFile::getExt($image_data['url_server']);
}
// Create original image hover with new name (upload from client)
if (count($images_hover) && !empty($images_hover['tmp_name'])) {
// Get image hover file type
$image_hoverType = JFile::getExt($images_hover['name']);
$image_hoverType = strtolower($image_hoverType);
// Get image hover's mime type
$image_hoverMimeType = $images_hover['type'];
// Get image's size
$image_hoverSize = $images_hover['size'];
$path_hover = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR;
$path_hover .= $data->alias . '-' . $data->id . '-h_o';
$path_hover .= '.' . JFile::getExt($images_hover['name']);
if ($input->getCmd('task') == 'save2copy' && $input->getInt('id')) {
$image_data['url_hover_server'] = null;
}
} elseif (isset($image_data['url_hover_server']) && !empty($image_data['url_hover_server'])) {
// Create original image with new name (upload from server)
// Get image hover file type
$image_hoverType = JFile::getExt($image_data['url_hover_server']);
$image_hoverType = strtolower($image_hoverType);
// Get image hover's mime type
$imageObj->loadFile(JPATH_ROOT . DIRECTORY_SEPARATOR . $image_data['url_hover_server']);
$image_hoverMimeType = $imageObj->getImageFileProperties($imageObj->getPath());
$image_hoverMimeType = $image_hoverMimeType->mime;