Exemplo n.º 1
0
 public function create()
 {
     $output = '';
     $size = JRequest::getCmd('size', '');
     if (!in_array($size, array('min', 'medium'))) {
         throw new Exception('The image size is not recognized', 500);
     }
     $image = JRequest::getVar('image', '');
     $id = JRequest::getInt('id', 0);
     $imagePath = JPATH_ROOT . DS . 'images' . DS . 'com_jea' . DS . 'images' . DS . $id . DS . $image;
     $thumbDir = JPATH_ROOT . DS . 'images' . DS . 'com_jea' . DS . 'thumb-' . $size;
     $thumbPath = $thumbDir . DS . $id . '-' . $image;
     if (file_exists($thumbPath)) {
         $output = readfile($thumbPath);
     } elseif (file_exists($imagePath)) {
         if (!JFolder::exists($thumbPath)) {
             JFolder::create($thumbDir);
         }
         $params = JComponentHelper::getParams('com_jea');
         if ($size == 'medium') {
             $width = $params->get('thumb_medium_width', 400);
             $height = $params->get('thumb_medium_height', 300);
         } else {
             $width = $params->get('thumb_min_width', 120);
             $height = $params->get('thumb_min_height', 90);
         }
         $quality = (int) $params->get('jpg_quality', 90);
         $cropThumbnails = (bool) $params->get('crop_thumbnails', 0);
         $JImage = new JImage($imagePath);
         if ($cropThumbnails) {
             $thumb = $JImage->resize($width, $height, true, JImage::SCALE_OUTSIDE);
             $left = $thumb->getWidth() > $width ? intval(($thumb->getWidth() - $width) / 2) : 0;
             $top = $thumb->getHeight() > $height ? intval(($thumb->getHeight() - $height) / 2) : 0;
             $thumb->crop($width, $height, $left, $top, false);
         } else {
             $thumb = $JImage->resize($width, $height);
         }
         $thumb->toFile($thumbPath, IMAGETYPE_JPEG, array('quality' => $quality));
         $output = readfile($thumbPath);
     } else {
         throw new Exception('The image ' . $image . ' was not found', 500);
     }
     JResponse::setHeader('Content-Type', 'image/jpeg', true);
     JResponse::setHeader('Content-Transfer-Encoding', 'binary');
     JResponse::allowCache(false);
     JResponse::setBody($output);
     echo JResponse::toString();
     exit;
 }
Exemplo n.º 2
0
 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";
     }
 }
Exemplo n.º 3
0
 /**
  * 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;
 }
Exemplo n.º 4
0
 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";
     }
 }
Exemplo n.º 5
0
 public function resize($type, $width, $height, $crop = false)
 {
     if ($type == 'thumbnail') {
         $path = $this->gallery->getThumbnailsPath();
         $filePath =& $this->thumbnailFilepath;
         $scale = 3;
         // SCALE_OUTSIDE
         $options = array('quality' => 75);
         // TODO as param
     } else {
         if ($type == 'resized') {
             $path = $this->gallery->getResizedPath();
             $filePath =& $this->resizedFilepath;
             $scale = 2;
             // SCALE_INSIDE
             $options = array('quality' => 85);
             // TODO as param
         } else {
             return;
         }
     }
     // define file paths
     $newPhotoFilepath = $path . DS . $this->folder->getFolderPath() . DS . $this->filename;
     $photoFilepath = $this->gallery->getPhotosPath() . DS . $this->folder->getFolderPath() . DS . $this->filename;
     // check if thumbnail already exists and create it if not
     if (!JFile::exists($newPhotoFilepath)) {
         // TODO add check if file size (width and height) is correct
         // resize image
         $photo = new JImage($photoFilepath);
         $newPhoto = $photo->resize($width, $height, true, $scale);
         // crop image
         if ($crop) {
             $offsetLeft = ($newPhoto->getWidth() - $width) / 2;
             $offsetTop = ($newPhoto->getHeight() - $height) / 2;
             $newPhoto->crop($width, $height, $offsetLeft, $offsetTop, false);
         }
         // create folders (recursive) and write file
         if (JFolder::create($path . DS . $this->folder->getFolderPath())) {
             $newPhoto->toFile($newPhotoFilepath, IMAGETYPE_JPEG, $options);
         }
     }
     $filePath = str_replace($this->gallery->getCachePath(), '', $newPhotoFilepath);
 }
Exemplo n.º 6
0
 $mime_types = $sconfig->mime_types;
 $okMIMETypes = $mime_types;
 $validFileTypes = explode(",", $okMIMETypes);
 if (is_int($imageinfo[0]) || is_int($imageinfo[1]) || in_array($imageinfo['mime'], $validFileTypes)) {
     $image['name'] = preg_replace("/[^A-Za-z.0-9]/i", "-", $image['name']);
     $newName = 'profile-' . $uid . '-' . $time . '-' . $image['name'];
     $newName2 = 'profile-x-' . $uid . '-' . $time . '-' . $image['name'];
     $uploadPath = $base_path . $uid . DS . $newName;
     $uploadPath2 = $base_path . $uid . DS . $newName2;
     $stampPath = JPATH_COMPONENT . DS . 'assets' . DS . 'images' . DS . 'stamp.png';
     $file_name = $newName2;
     JFile::upload($image['tmp_name'], $uploadPath);
     ####################
     $image = new JImage($uploadPath);
     $properties = JImage::getImageFileProperties($uploadPath);
     $resizedImage = $image->resize('250', '250', true);
     $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($uploadPath, $type);
     //create image .....
     //echo 'creem imaginea<br />';
     watermark_image($uploadPath, $uploadPath2, $mime);
     ####################
     ######adaugare in baza de date
     $upd_poza = ", `poza` = '" . $file_name . "'";
Exemplo n.º 7
0
 /**
  * Save user profile data.
  *
  * @param   array    $data    Entered user data
  * @param   boolean  $isNew   True if this is a new user
  * @param   boolean  $result  True if saving the user worked
  * @param   string   $error   Error message
  *
  * @return  boolean
  */
 public function onUserAfterSave($data, $isNew, $result, $error)
 {
     // Only run in front-end.
     if (!JFactory::getApplication()->isSite()) {
         return true;
     }
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $folder = $this->params->get('folder', '');
     $avatarFolder = JPATH_ROOT . '/' . $folder;
     // If the avatar folder doesn't exist, we don't do anything.
     if (!JFolder::exists($avatarFolder)) {
         return false;
     }
     $jinput = JFactory::getApplication()->input;
     $delete = $jinput->get('delete-avatar', '', 'word');
     if ($delete == 'yes') {
         $this->deleteAvatar($userId);
         return true;
     }
     if ($result && $userId > 0) {
         $files = $jinput->files->get('jform', array(), 'array');
         if (!isset($files['cmavatar']['cmavatar'])) {
             return false;
         }
         $file = $files['cmavatar']['cmavatar'];
         if (empty($file['name'])) {
             return true;
         }
         $fileTypes = explode('.', $file['name']);
         if (count($fileTypes) < 2) {
             // There seems to be no extension.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         array_shift($fileTypes);
         // Check if the file has an executable extension.
         $executable = array('php', 'js', 'exe', 'phtml', 'java', 'perl', 'py', 'asp', 'dll', 'go', 'ade', 'adp', 'bat', 'chm', 'cmd', 'com', 'cpl', 'hta', 'ins', 'isp', 'jse', 'lib', 'mde', 'msc', 'msp', 'mst', 'pif', 'scr', 'sct', 'shb', 'sys', 'vb', 'vbe', 'vbs', 'vxd', 'wsc', 'wsf', 'wsh');
         $check = array_intersect($fileTypes, $executable);
         if (!empty($check)) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         $fileType = array_pop($fileTypes);
         $allowable = array_map('trim', explode(',', $this->params->get('allowed_extensions')));
         if ($fileType == '' || $fileType == false || !in_array($fileType, $allowable)) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TYPE'));
             return false;
         }
         $uploadMaxSize = $this->params->get('max_size', 0) * 1024 * 1024;
         $uploadMaxFileSize = $this->toBytes(ini_get('upload_max_filesize'));
         if ($file['error'] == 1 || $uploadMaxSize > 0 && $file['size'] > $uploadMaxSize || $uploadMaxFileSize > 0 && $file['size'] > $uploadMaxFileSize) {
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_TOO_LARGE'));
             return false;
         }
         // Make the file name unique.
         $md5String = $userId . $file['name'] . JFactory::getDate();
         $avatarFileName = JFile::makeSafe(md5($md5String));
         if (empty($avatarFileName)) {
             // No file name after the name was cleaned by JFile::makeSafe.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_NO_FILENAME'));
             return false;
         }
         $avatarPath = JPath::clean($avatarFolder . '/' . $avatarFileName . '.' . $this->extension);
         if (JFile::exists($avatarPath)) {
             // A file with this name already exists. It is almost impossible.
             throw new RuntimeException(JText::_('PLG_USER_CMAVATAR_ERROR_FILE_EXISTS'));
             return false;
         }
         // Start resizing the file.
         $avatar = new JImage($file['tmp_name']);
         $originalWidth = $avatar->getWidth();
         $originalHeight = $avatar->getHeight();
         $ratio = $originalWidth / $originalHeight;
         $maxWidth = (int) $this->params->get('width', 100);
         $maxHeight = (int) $this->params->get('height', 100);
         // Invalid value in the plugin configuration. Set avatar width to 100.
         if ($maxWidth <= 0) {
             $maxWidth = 100;
         }
         if ($maxHeight <= 0) {
             $maxHeight = 100;
         }
         if ($originalWidth > $maxWidth) {
             $ratio = $originalWidth / $originalHeight;
             $newWidth = $maxWidth;
             $newHeight = $newWidth / $ratio;
             if ($newHeight > $maxHeight) {
                 $ratio = $newWidth / $newHeight;
                 $newHeight = $maxHeight;
                 $newWidth = $newHeight * $ratio;
             }
         } elseif ($originalHeight > $maxHeight) {
             $ratio = $originalWidth / $originalHeight;
             $newHeight = $maxHeight;
             $newWidth = $newHeight * $ratio;
             if ($newWidth > $maxWidth) {
                 $ratio = $newWidth / $newHeight;
                 $newWidth = $maxWidth;
                 $newHeight = $newWidth / $ratio;
             }
         } else {
             $newWidth = $originalWidth;
             $newHeight = $originalHeight;
         }
         $resizedAvatar = $avatar->resize($newWidth, $newHeight, true);
         $resizedAvatar->toFile($avatarPath);
         // Delete current avatar if exists.
         $this->deleteAvatar($userId);
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         // Save avatar's file name to database.
         if (!empty($currentAvatar)) {
             $query->update($db->qn('#__user_profiles'))->set($db->qn('profile_value') . ' = ' . $db->q($avatarFileName))->where($db->qn('user_id') . ' = ' . $db->q($userId))->where($db->qn('profile_key') . ' = ' . $db->quote($this->profileKey));
         } else {
             $query->insert($db->qn('#__user_profiles'))->columns($db->qn(array('user_id', 'profile_key', 'profile_value', 'ordering')))->values($db->q($userId) . ', ' . $db->q($this->profileKey) . ', ' . $db->q($avatarFileName) . ', ' . $db->q('1'));
         }
         $db->setQuery($query)->execute();
         // Check for a database error.
         if ($error = $db->getErrorMsg()) {
             throw new RuntimeException($error);
             return false;
         }
     }
     return true;
 }
Exemplo n.º 8
0
 /**
  * Store the file in a folder of the extension.
  *
  * @param array $image
  * @param bool $resizeImage
  *
  * @throws \RuntimeException
  * @throws \Exception
  * @throws \InvalidArgumentException
  *
  * @return array
  */
 public function uploadImage($image, $resizeImage = false)
 {
     $app = JFactory::getApplication();
     /** @var $app JApplicationSite */
     $uploadedFile = ArrayHelper::getValue($image, 'tmp_name');
     $uploadedName = ArrayHelper::getValue($image, 'name');
     $errorCode = ArrayHelper::getValue($image, 'error');
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     $filesystemHelper = new Prism\Filesystem\Helper($params);
     $mediaFolder = $filesystemHelper->getMediaFolder();
     $destinationFolder = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $mediaFolder);
     $temporaryFolder = $app->get('tmp_path');
     // Joomla! media extension parameters
     $mediaParams = JComponentHelper::getParams('com_media');
     /** @var $mediaParams Joomla\Registry\Registry */
     $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 validators.
     $sizeValidator = new Prism\File\Validator\Size($fileSize, $uploadMaxSize);
     $serverValidator = new Prism\File\Validator\Server($errorCode, array(UPLOAD_ERR_NO_FILE));
     $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($serverValidator)->addValidator($imageValidator);
     // Validate the file
     if (!$file->isValid()) {
         throw new RuntimeException($file->getError());
     }
     // Generate temporary file name
     $ext = strtolower(JFile::makeSafe(JFile::getExt($image['name'])));
     $generatedName = Prism\Utilities\StringHelper::generateRandomString();
     $temporaryFile = $generatedName . '_reward.' . $ext;
     $temporaryDestination = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $temporaryFile);
     // Prepare uploader object.
     $uploader = new Prism\File\Uploader\Local($uploadedFile);
     $uploader->setDestination($temporaryDestination);
     // Upload temporary file
     $file->setUploader($uploader);
     $file->upload();
     $temporaryFile = $file->getFile();
     if (!is_file($temporaryFile)) {
         throw new Exception('COM_GAMIFICATION_ERROR_FILE_CANT_BE_UPLOADED');
     }
     // Resize image
     $image = new JImage();
     $image->loadFile($temporaryFile);
     if (!$image->isLoaded()) {
         throw new Exception(JText::sprintf('COM_GAMIFICATION_ERROR_FILE_NOT_FOUND', $temporaryDestination));
     }
     $imageName = $generatedName . '_image.png';
     $smallName = $generatedName . '_small.png';
     $squareName = $generatedName . '_square.png';
     $imageFile = $destinationFolder . DIRECTORY_SEPARATOR . $imageName;
     $smallFile = $destinationFolder . DIRECTORY_SEPARATOR . $smallName;
     $squareFile = $destinationFolder . DIRECTORY_SEPARATOR . $squareName;
     $scaleOption = $params->get('image_resizing_scale', JImage::SCALE_INSIDE);
     // Create main image
     if (!$resizeImage) {
         $image->toFile($imageFile, IMAGETYPE_PNG);
     } else {
         $width = $params->get('image_width', 200);
         $height = $params->get('image_height', 200);
         $image->resize($width, $height, false, $scaleOption);
         $image->toFile($imageFile, IMAGETYPE_PNG);
     }
     // Create small image
     $width = $params->get('image_small_width', 100);
     $height = $params->get('image_small_height', 100);
     $image->resize($width, $height, false, $scaleOption);
     $image->toFile($smallFile, IMAGETYPE_PNG);
     // Create square image
     $width = $params->get('image_square_width', 50);
     $height = $params->get('image_square_height', 50);
     $image->resize($width, $height, false, $scaleOption);
     $image->toFile($squareFile, IMAGETYPE_PNG);
     $names = array('image' => $imageName, 'image_small' => $smallName, 'image_square' => $squareName);
     // Remove the temporary file.
     if (JFile::exists($temporaryFile)) {
         JFile::delete($temporaryFile);
     }
     return $names;
 }
Exemplo n.º 9
0
 /**
  * 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);
     $image->resize($width, $height, false);
     $image->toFile($iconFile, IMAGETYPE_PNG);
     // Remove the temporary file
     if (JFile::exists($tmpSourceFile)) {
         JFile::delete($tmpSourceFile);
     }
     return $names = array("image" => $imageName, "image_small" => $smallName, "image_icon" => $iconName, "image_square" => $squareName);
 }
Exemplo n.º 10
0
 /**
  * Crop the image and generates smaller ones.
  *
  * @param string $file
  * @param array $options
  * @param Joomla\Registry\Registry $params
  *
  * @throws Exception
  *
  * @return array
  */
 public function cropImage($file, $options, $params)
 {
     // Resize image
     $image = new JImage();
     $image->loadFile($file);
     if (!$image->isLoaded()) {
         throw new Exception(JText::sprintf('COM_SOCIALCOMMUNITY_ERROR_FILE_NOT_FOUND', $file));
     }
     $destinationFolder = Joomla\Utilities\ArrayHelper::getValue($options, 'destination');
     // Generate temporary file name
     $generatedName = Prism\Utilities\StringHelper::generateRandomString(24);
     $profileName = $generatedName . '_profile.png';
     $smallName = $generatedName . '_small.png';
     $squareName = $generatedName . '_square.png';
     $iconName = $generatedName . '_icon.png';
     $imageFile = JPath::clean($destinationFolder . DIRECTORY_SEPARATOR . $profileName);
     $smallFile = JPath::clean($destinationFolder . DIRECTORY_SEPARATOR . $smallName);
     $squareFile = JPath::clean($destinationFolder . DIRECTORY_SEPARATOR . $squareName);
     $iconFile = JPath::clean($destinationFolder . DIRECTORY_SEPARATOR . $iconName);
     // Create profile image.
     $width = Joomla\Utilities\ArrayHelper::getValue($options, 'width', 200);
     $width = $width < 25 ? 50 : $width;
     $height = Joomla\Utilities\ArrayHelper::getValue($options, 'height', 200);
     $height = $height < 25 ? 50 : $height;
     $left = Joomla\Utilities\ArrayHelper::getValue($options, 'x', 0);
     $top = Joomla\Utilities\ArrayHelper::getValue($options, 'y', 0);
     $image->crop($width, $height, $left, $top, false);
     // Resize to general size.
     $width = $params->get('image_width', 200);
     $width = $width < 25 ? 50 : $width;
     $height = $params->get('image_height', 200);
     $height = $height < 25 ? 50 : $height;
     $image->resize($width, $height, false);
     // Store to file.
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Create small image.
     $width = $params->get('image_small_width', 100);
     $height = $params->get('image_small_height', 100);
     $image->resize($width, $height, false);
     $image->toFile($smallFile, IMAGETYPE_PNG);
     // Create square image.
     $width = $params->get('image_square_width', 50);
     $height = $params->get('image_square_height', 50);
     $image->resize($width, $height, false);
     $image->toFile($squareFile, IMAGETYPE_PNG);
     // Create icon image.
     $width = $params->get('image_icon_width', 25);
     $height = $params->get('image_icon_height', 25);
     $image->resize($width, $height, false);
     $image->toFile($iconFile, IMAGETYPE_PNG);
     $names = array('image_profile' => $profileName, 'image_small' => $smallName, 'image_square' => $squareName, 'image_icon' => $iconName);
     // Remove the temporary file.
     if (JFile::exists($file)) {
         JFile::delete($file);
     }
     return $names;
 }
Exemplo n.º 11
0
 /**
  * Resize the temporary file to new one.
  *
  * <code>
  * $image = $this->input->files->get('media', array(), 'array');
  * $rootFolder = "/root/joomla/tmp";
  *
  * $resizeOptions = array(
  *    'width'  => $options['thumb_width'],
  *    'height' => $options['thumb_height'],
  *    'scale'  => $options['thumb_scale']
  * );
  *
  * $file = new Prism\File\Image($image, $rootFolder);
  *
  * $file->upload();
  * $fileData = $file->resize($resize);
  * </code>
  *
  * @param array $options
  * @param bool $replace Replace the original file with the new one.
  * @param string $prefix Filename prefix.
  *
  * @throws \RuntimeException
  *
  * @return array
  */
 public function resize(array $options, $replace = false, $prefix = '')
 {
     if (!$this->file) {
         throw new \RuntimeException(\JText::sprintf('LIB_PRISM_ERROR_FILE_NOT_FOUND_S', $this->file));
     }
     // Resize image.
     $image = new \JImage();
     $image->loadFile($this->file);
     if (!$image->isLoaded()) {
         throw new \RuntimeException(\JText::sprintf('LIB_PRISM_ERROR_FILE_NOT_FOUND_S', $this->file));
     }
     // Resize to general size.
     $width = ArrayHelper::getValue($options, 'width', 640);
     $width = $width < 50 ? 50 : $width;
     $height = ArrayHelper::getValue($options, 'height', 480);
     $height = $height < 50 ? 50 : $height;
     $scale = ArrayHelper::getValue($options, 'scale', \JImage::SCALE_INSIDE);
     $image->resize($width, $height, false, $scale);
     // Generate new name.
     $generatedName = StringHelper::generateRandomString($this->options->get('filename_length', 16)) . '.png';
     if (is_string($prefix) and $prefix !== '') {
         $generatedName = $prefix . $generatedName;
     }
     $file = \JPath::clean($this->rootFolder . '/' . $generatedName);
     // Store to file.
     $image->toFile($file, IMAGETYPE_PNG);
     if ($replace) {
         \JFile::delete($this->file);
         $this->file = $file;
     }
     // Prepare meta data about the file.
     $fileData = array('filename' => $generatedName, 'filepath' => $file, 'type' => 'image');
     $fileData = array_merge($fileData, $this->prepareImageProperties($this->file));
     return $fileData;
 }
Exemplo n.º 12
0
 public static function profileImage($profileID, $variable = 'profile')
 {
     $files = JRequest::getVar('jform', null, 'files');
     $jform = JRequest::getVar('jform', null, 'ARRAY');
     // Check that user want upload image or delete image
     $image_delete = empty($jform[$variable]['image_delete']) ? false : true;
     $image_error = empty($variable) ? $files['error']['image'] : $files['error'][$variable]['image'];
     $image_tmp_name = empty($variable) ? $files['tmp_name']['image'] : $files['tmp_name'][$variable]['image'];
     // Minimum image size
     $imageSize = 200;
     $profileImage = -1;
     // Upload Profile Image
     if ($image_error == 0 && !$image_delete) {
         // Resize Image
         $image = new JImage($image_tmp_name);
         $sourceWidth = $image->getWidth();
         $sourceHeight = $image->getHeight();
         if ($sourceWidth < $imageSize || $sourceHeight < $imageSize) {
             return JText::sprintf('COM_SIBDIET_ERROR_PROFILE_IMAGE_TOO_SMALL', $imageSize);
         }
         // Set image name to user profile ID
         $image_filename = $profileID . '.jpg';
         $ratio = max($sourceWidth, $sourceHeight) / $imageSize;
         $ratio = max($ratio, 1.0);
         $resizedWidth = (int) ($sourceWidth / $ratio);
         $resizedHeight = (int) ($sourceHeight / $ratio);
         $resized = $image->resize($resizedWidth, $resizedHeight, true, JImage::SCALE_INSIDE);
         $resized->toFile(JPATH_ROOT . '/images/sibdiet/profiles/' . $image_filename, 'IMAGETYPE_JPEG');
     } elseif ($image_delete) {
         $image_path = JPATH_ROOT . '/images/sibdiet/profiles/' . $profileID . '.jpg';
         jimport('joomla.filesystem.file');
         if (JFile::exists($image_path)) {
             JFile::delete($image_path);
         }
     }
     return true;
 }
Exemplo n.º 13
0
 public static function crop($srcPath, $destPath, $cropWidth, $cropHeight, $sourceX, $sourceY, $cropMaxWidth = 64, $cropMaxHeight = 64)
 {
     $jImage = new JImage($srcPath);
     $imageInfo = JImage::getImageFileProperties($srcPath);
     try {
         if ($cropWidth == 0 && $cropHeight == 0) {
             $cropThumb = $jImage->resize($cropMaxWidth, $cropMaxHeight);
         } else {
             $cropThumb = $jImage->crop($cropWidth, $cropHeight, $sourceX, $sourceY, true);
             if ($cropMaxWidth <= $cropWidth || $cropMaxHeight <= $cropHeight) {
                 $cropThumb = $cropThumb->resize($cropMaxWidth, $cropMaxHeight);
             }
         }
         $option = $imageInfo->type == IMAGETYPE_PNG ? self::$pngOption : self::$otherOption;
         $cropThumb->toFile($destPath, $imageInfo->type, $option);
     } catch (Exception $ex) {
         return false;
     }
     return true;
 }
Exemplo n.º 14
0
 public static function resize($filename, $width, $height)
 {
     $path = JPath::clean($filename);
     $JImage = new JImage($path);
     $info = pathinfo($filename);
     $extension = $info['extension'];
     $old_image = basename($filename);
     $new_image = $info['filename'] . '-' . $width . 'x' . $height . '.' . $extension;
     $ret = '';
     if (!file_exists(DIR_IMAGE . '/thumbs' . $new_image) || filemtime(DIR_IMAGE . '/' . $old_image) > filemtime(DIR_IMAGE . '/thumbs' . $new_image)) {
         $path = '';
         $directories = explode('/', dirname(str_replace('../', '', DIR_IMAGE . '/thumbs' . $new_image)));
         foreach ($directories as $directory) {
             if (!empty($directory)) {
                 $path = $path . '/' . $directory;
                 if (!file_exists($path)) {
                     @mkdir(DIR_IMAGE . $path, 0777);
                 }
             }
         }
         $image = $JImage->resize($width, $height, true, 1);
         if ($image->toFile(DIR_IMAGE . '/thumbs' . $new_image)) {
             $ret = JUri::root() . 'media/openhrm/images/thumbs' . $new_image;
         }
     } else {
         $ret = JUri::root() . 'media/openhrm/images/thumbs' . $new_image;
     }
     return $ret;
 }
Exemplo n.º 15
0
 public function validateInput()
 {
     jimport('joomla.filesystem.file');
     jimport('joomla.image.image');
     $app = JFactory::getApplication();
     $fm = JRequest::getVar('jform', NULL, 'post');
     if (!empty($fm)) {
         $site_name = $fm['site_name'];
         $site_metadesc = $fm['site_metadesc'];
         $site_metakeys = $fm['site_metakeys'];
         $site_offline = $fm['site_offline'];
         $admin_email = $fm['admin_email'];
         $admin_user = $fm['admin_user'];
         $admin_password = $fm['admin_password'];
         $admin_password2 = $fm['admin_password2'];
     } else {
         $site_name = NULL;
         $site_metadesc = NULL;
         $site_metakeys = NULL;
         $site_offline = NULL;
         $admin_email = NULL;
         $admin_user = NULL;
         $admin_password = NULL;
         $admin_password2 = NULL;
     }
     $files = JRequest::getVar('jform', NULL, 'files');
     $msg = "Usted debe corregir y completar los siguientes datos antes de continuar:<br />";
     $disc = true;
     if (empty($site_name)) {
         $msg .= "- Debe ingresar un nombre para el sitio.<br />";
         $disc &= false;
     }
     if (empty($admin_email)) {
         $msg .= "- Debe ingresar el correo del administrador.<br />";
         $disc &= false;
     }
     if (empty($admin_user)) {
         $msg .= "- Debe ingresar un nombre de usuario.<br />";
         $disc &= false;
     }
     if (empty($admin_password)) {
         $msg .= "- Debe ingresar una contraseña.<br />";
         $disc &= false;
     }
     if (empty($admin_password2)) {
         $msg .= "- Debe confirmar la contraseña.<br />";
         $disc &= false;
     }
     if ($admin_password != $admin_password2) {
         $msg .= "- Las contraseñas no coinciden.<br />";
         $disc &= false;
     }
     if ($disc) {
         if (!empty($files['tmp_name']['site_logo'])) {
             // Set the path to the file
             $file = $files['tmp_name']['site_logo'];
             // Instantiate our JImage object
             $image = new JImage($file);
             // Get the file's properties
             $properties = $image->getImageFileProperties($file);
             // Resize the file as a new object
             $logo1 = $image->resize('200px', '74px', true);
             $logo3 = $image->resize('250px', '30px', true);
             // Determine the MIME of the original file to get the proper type for output
             $mime = $properties->mime;
             if ($mime == 'image/jpeg') {
                 $type = IMAGETYPE_JPEG;
             } elseif ($mime == 'image/png') {
                 $type = IMAGETYPE_PNG;
             } elseif ($mime == 'image/gif') {
                 $type = IMAGETYPE_GIF;
             }
             // Store the resized image to a new file
             $logo1->toFile(JPATH_ROOT . DS . 'images' . DS . 'logos' . DS . 'jokte-logo-front.png', $type);
             $logo3->toFile(JPATH_ROOT . DS . 'administrator' . DS . 'templates' . DS . 'storkantu' . DS . 'images' . DS . 'logo.png', $type);
         }
         $site_name = $fm['site_name'];
         $site_metadesc = $fm['site_metadesc'];
         $site_metakeys = $fm['site_metakeys'];
         $site_offline = $fm['site_offline'];
         $admin_email = $fm['admin_email'];
         $admin_user = $fm['admin_user'];
         $admin_password = $fm['admin_password'];
         $admin_password2 = $fm['admin_password2'];
         $fmData = '&jform[site_name]=' . $site_name;
         $fmData .= '&jform[site_metadesc]=' . $site_metadesc;
         $fmData .= '&jform[site_metakeys]=' . $site_metakeys;
         $fmData .= '&jform[site_offline]=' . $site_offline;
         $fmData .= '&jform[admin_email]=' . $admin_email;
         $fmData .= '&jform[admin_user]=' . $admin_user;
         $fmData .= '&jform[admin_password]=' . $admin_password;
         $fmData .= '&jform[admin_password2]=' . $admin_password2;
         JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
         $app->redirect('?view=remove&task=setup.saveconfig' . $fmData . "&{$tkn}=1");
     } elseif (!empty($fm)) {
         JRequest::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
         $app->redirect('?view=site', $msg, 'warning');
     }
 }
Exemplo n.º 16
0
 function uploadImages($file, $url = 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_plus';
         $tzUserFolder = 'categories';
         $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>'));
                 }
             }
         }
         $params = JComponentHelper::getParams('com_tz_portfolio_plus');
         if (!$url) {
             $image = new JImage(JPATH_SITE . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $file));
             $desFileName = 'categories_' . time() . uniqid() . '.' . JFile::getExt($file);
             $desPath = $tzUserFolderPath . DIRECTORY_SEPARATOR . $desFileName;
             if ($params->get('tz_catimage_width', 400)) {
                 $newWidth = $params->get('tz_catimage_width', 400);
             }
             $type = strtolower(JFile::getExt($file));
             $_type = null;
             if ($type == 'gif') {
                 $_type = IMAGETYPE_GIF;
             } elseif ($type == 'png') {
                 $_type = IMAGETYPE_PNG;
             }
             $height = ceil($image->getHeight() * $newWidth / $image->getWidth());
             $image = $image->resize($newWidth, $height);
             $image->toFile($desPath, $_type);
             return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
         } else {
             tzportfolioplusimport('HTTPFetcher');
             tzportfolioplusimport('readfile');
             $image = new Services_Yadis_PlainHTTPFetcher();
             $image = $image->get($file);
             if (!in_array($image->headers['Content-Type'], $arr)) {
                 $this->setError(JText::_('COM_TZ_PORTFOLIO_PLUS_INVALID_FILE'));
                 return false;
             }
             if ($image->headers['Content-Length'] > $maxSize) {
                 $this->setError(JText::_('COM_TZ_PORTFOLIO_PLUS_IMAGE_SIZE_TOO_LARGE'));
                 return false;
             }
             $desFileName = 'categories_' . 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_PLUS_CAN_NOT_UPLOADED_FILEs'));
                     return false;
                 }
                 $image = new JImage($desPath);
                 $newWidth = $params->get('tz_catimage_width', 400);
                 $newHeight = ceil($image->getHeight() * $newWidth / $image->getWidth());
                 $newImage = $image->resize((int) $newWidth, $newHeight, false);
                 $type = strtolower(JFile::getExt($file));
                 $_type = $type == 'gif' ? IMAGETYPE_GIF : $type == 'png' ? IMAGETYPE_PNG : null;
                 $newImage->toFile($desPath, $_type);
                 return 'media/' . $tzFolder . '/' . $tzUserFolder . '/' . $desFileName;
             }
         }
     }
     return true;
 }
Exemplo n.º 17
0
 public function save($data)
 {
     $app = JFactory::getApplication();
     $input = $app->input;
     $_data = array('id' => $data->id, 'asset_id' => $data->asset_id, 'media' => '{}');
     $params = $this->getState('params');
     // Get some params
     $mime_types = $params->get('image_mime_type', 'image/jpeg,image/gif,image/png,image/bmp');
     $mime_types = explode(',', $mime_types);
     $file_types = $params->get('image_file_type', 'bmp,gif,jpg,jpeg,png');
     $file_types = explode(',', $file_types);
     $file_sizes = $params->get('image_file_size', 10);
     $file_sizes = $file_sizes * 1024 * 1024;
     // Get and Process data
     $image_data = $input->get('jform', null, 'array');
     if (isset($image_data['media'])) {
         if (isset($image_data['media'][$this->getName()])) {
             $image_data = $image_data['media']['image'];
         }
     }
     $media = null;
     if ($data->media && !empty($data->media)) {
         $media = new JRegistry();
         $media->loadString($data->media);
         $media = $media->get('image');
     }
     // Set data when save as copy article
     if ($input->getCmd('task') == 'save2copy' && $input->getInt('id')) {
         if (isset($image_data['url_remove']) && $image_data['url_remove']) {
             $image_data['url_remove'] = null;
             $image_data['url'] = '';
         }
         if (isset($image_data['url_hover_remove']) && $image_data['url_hover_remove']) {
             $image_data['url_hover_remove'] = '';
             $image_data['url_hover'] = '';
         }
         if (!isset($image_data['url_server']) || isset($image_data['url_server']) && empty($image_data['url_server'])) {
             if (isset($image_data['url']) && $image_data['url']) {
                 $ext = JFile::getExt($image_data['url']);
                 $path_copy = str_replace('.' . $ext, '_o.' . $ext, $image_data['url']);
                 if (JFile::exists(JPATH_ROOT . DIRECTORY_SEPARATOR . $path_copy)) {
                     $image_data['url_server'] = $path_copy;
                     $image_data['url'] = '';
                 }
             }
         }
         if (!isset($image_data['url_hover_server']) || isset($image_data['url_hover_server']) && empty($image_data['url_hover_server'])) {
             if (isset($image_data['url_hover']) && $image_data['url_hover']) {
                 $ext = JFile::getExt($image_data['url_hover']);
                 $path_copy = str_replace('.' . $ext, '_o.' . $ext, $image_data['url_hover']);
                 if (JFile::exists(JPATH_ROOT . DIRECTORY_SEPARATOR . $path_copy)) {
                     $image_data['url_hover_server'] = $path_copy;
                     $image_data['url_hover'] = '';
                 }
             }
         }
     }
     // Remove image and image hover with resized
     if ($image_size = $params->get('image_size', array())) {
         $image_size = $this->prepareImageSize($image_size);
         if (is_array($image_size) && count($image_size)) {
             foreach ($image_size as $_size) {
                 $size = json_decode($_size);
                 // Delete old image files
                 if (isset($image_data['url_remove']) && $image_data['url_remove'] && $media && isset($media->url) && !empty($media->url)) {
                     $image_url = $media->url;
                     $image_url = str_replace('.' . JFile::getExt($image_url), '_' . $size->image_name_prefix . '.' . JFile::getExt($image_url), $image_url);
                     JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url));
                 }
                 // Delete old image hover files
                 if (isset($image_data['url_hover_remove']) && $image_data['url_hover_remove'] && $media && isset($media->url_hover) && !empty($media->url_hover)) {
                     $image_url = $media->url_hover;
                     $image_url = str_replace('.' . JFile::getExt($image_url), '_' . $size->image_name_prefix . '.' . JFile::getExt($image_url), $image_url);
                     JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url));
                 }
             }
         }
     }
     // Remove Image file when tick to remove file box
     if (isset($image_data['url_remove']) && $image_data['url_remove']) {
         // Before upload image to file must delete original file
         if ($media && isset($media->url) && !empty($media->url)) {
             $image_url = $media->url;
             $image_url = str_replace('.' . JFile::getExt($image_url), '_o' . '.' . JFile::getExt($image_url), $image_url);
             if (JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url))) {
                 $image_data['url'] = '';
                 unset($image_data['url_remove']);
             }
         }
     } else {
         unset($image_data['url']);
     }
     // Remove Image hover file when tick to remove file box
     if (isset($image_data['url_hover_remove']) && $image_data['url_hover_remove']) {
         // Before upload image to file must delete original file
         if ($media && isset($media->url_hover) && !empty($media->url_hover)) {
             $image_url = $media->url_hover;
             $image_url = str_replace('.' . JFile::getExt($image_url), '_o' . '.' . JFile::getExt($image_url), $image_url);
             if (JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url))) {
                 $image_data['url_hover'] = '';
                 unset($image_data['url_hover_remove']);
             }
         }
     } else {
         unset($image_data['url_hover']);
     }
     $images = array();
     $images_hover = array();
     $imageObj = new JImage();
     // Upload image or image hover
     if ($files = $input->files->get('jform', array(), 'array')) {
         if (isset($files['media']) && isset($files['media']['image'])) {
             $files = $files['media']['image'];
             // Get image from form
             if (isset($files['url_client']['name']) && !empty($files['url_client']['name'])) {
                 $images = $files['url_client'];
             }
             // Get image hover data from form
             if (isset($files['url_hover_client']['name']) && !empty($files['url_hover_client']['name'])) {
                 $images_hover = $files['url_hover_client'];
             }
         }
     }
     $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;
         // Get image hover's size
         $image_hoverSize = $image_hoverMimeType->filesize;
         $path_hover = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR;
         $path_hover .= $data->alias . '-' . $data->id . '-h_o';
         $path_hover .= '.' . JFile::getExt($image_data['url_hover_server']);
     }
     // Upload original image
     if ($path && !empty($path)) {
         //-- Check image information --//
         // Check MIME Type
         if (!in_array($imageMimeType, $mime_types)) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNINVALID_MIME'), 'notice');
             return false;
         }
         // Check file type
         if (!in_array($imageType, $file_types)) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNFILETYPE'), 'notice');
             return false;
         }
         // Check file size
         if ($imageSize > $file_sizes) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNFILETOOLARGE'), 'notice');
             return false;
         }
         //-- End check image information --//
         // Before upload image to file must delete original file
         if ($media && isset($media->url) && !empty($media->url)) {
             $image_url = $media->url;
             $image_url = str_replace('.' . JFile::getExt($image_url), '_o' . '.' . JFile::getExt($image_url), $image_url);
             JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url));
         }
         if (isset($images['tmp_name']) && !empty($images['tmp_name']) && !JFile::upload($images['tmp_name'], $path)) {
             $path = '';
         } elseif (isset($image_data['url_server']) && !empty($image_data['url_server']) && !JFile::copy(JPATH_ROOT . DIRECTORY_SEPARATOR . $image_data['url_server'], $path)) {
             $path = '';
         }
     }
     // Upload original image hover
     if ($path_hover && !empty($path_hover)) {
         //-- Check image information --//
         // Check MIME Type
         if (!in_array($image_hoverMimeType, $mime_types)) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNINVALID_MIME'), 'notice');
             return false;
         }
         // Check file type
         if (!in_array($image_hoverType, $file_types)) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNFILETYPE'), 'notice');
             return false;
         }
         // Check file size
         if ($image_hoverSize > $file_sizes) {
             $app->enqueueMessage(JText::_('PLG_MEDIATYPE_IMAGE_ERROR_WARNFILETOOLARGE'), 'notice');
             return false;
         }
         //-- End check image information --//
         // Before upload image hover file to file must delete original file
         if ($media && isset($media->url_hover) && !empty($media->url_hover)) {
             $image_url = $media->url_hover;
             $image_url = str_replace('.' . JFile::getExt($image_url), '_o' . '.' . JFile::getExt($image_url), $image_url);
             JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url));
         }
         if (isset($images_hover['tmp_name']) && !empty($images_hover['tmp_name']) && !JFile::upload($images_hover['tmp_name'], $path_hover)) {
             $path_hover = '';
         } elseif (isset($image_data['url_hover_server']) && !empty($image_data['url_hover_server']) && !JFile::copy(JPATH_ROOT . DIRECTORY_SEPARATOR . $image_data['url_hover_server'], $path_hover)) {
             $path_hover = '';
         }
     }
     // Upload image and image hover with resize
     if ($image_size = $params->get('image_size')) {
         $image_size = $this->prepareImageSize($image_size);
         $image = null;
         $image_hover = null;
         if (is_array($image_size) && count($image_size)) {
             foreach ($image_size as $_size) {
                 $size = json_decode($_size);
                 // Upload image with resize
                 if ($path) {
                     // Create new ratio from new with of image size param
                     $imageObj->loadFile($path);
                     $imgProperties = $imageObj->getImageFileProperties($imageObj->getPath());
                     $newH = $imgProperties->height * $size->width / $imgProperties->width;
                     $newImage = $imageObj->resize($size->width, $newH);
                     $newPath = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR . $data->alias . '-' . $data->id . '_' . $size->image_name_prefix . '.' . JFile::getExt($path);
                     // Before generate image to file must delete old files
                     if ($media && isset($media->url) && !empty($media->url)) {
                         $image_url = $media->url;
                         $image_url = str_replace('.' . JFile::getExt($image_url), '_' . $size->image_name_prefix . '.' . JFile::getExt($image_url), $image_url);
                         JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url));
                     }
                     // Generate image to file
                     $newImage->toFile($newPath, $imgProperties->type);
                 }
                 // Upload image hover with resize
                 if ($path_hover) {
                     // Create new ratio from new with of image size param
                     $imageObj->loadFile($path_hover);
                     $imgHoverProperties = $imageObj->getImageFileProperties($imageObj->getPath());
                     $newH = $imgHoverProperties->height * $size->width / $imgHoverProperties->width;
                     $newHImage = $imageObj->resize($size->width, $newH);
                     $newHPath = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_ROOT . DIRECTORY_SEPARATOR . $data->alias . '-' . $data->id . '-h_' . $size->image_name_prefix . '.' . JFile::getExt($path_hover);
                     // Before generate image hover to file must delete old files
                     if ($media && isset($media->url_hover) && !empty($media->url_hover)) {
                         $image_url_hover = $media->url_hover;
                         $image_url_hover = str_replace('.' . JFile::getExt($image_url_hover), '_' . $size->image_name_prefix . '.' . JFile::getExt($image_url_hover), $image_url_hover);
                         JFile::delete(JPATH_ROOT . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $image_url_hover));
                     }
                     // Generate image to file
                     $newHImage->toFile($newHPath, $imgHoverProperties->type);
                 }
             }
         }
     }
     if ($path && !empty($path)) {
         $image_data['url'] = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_BASE . '/' . $data->alias . '-' . $data->id . '.' . JFile::getExt($path);
     }
     if ($path_hover && !empty($path_hover)) {
         $image_data['url_hover'] = COM_TZ_PORTFOLIO_PLUS_MEDIA_ARTICLE_BASE . '/' . $data->alias . '-' . $data->id . '-h.' . JFile::getExt($path_hover);
     }
     unset($image_data['url_server']);
     unset($image_data['url_hover_server']);
     $this->__save($data, $image_data);
     //        }
 }
Exemplo n.º 18
0
 /**
  * Resize an image.
  *
  * @param   string  $file    The name and location of the file
  * @param   string  $width   The new width of the image.
  * @param   string  $height  The new height of the image.
  *
  * @return   boolean  true if image resize successful, false otherwise.
  *
  * @since   3.2
  */
 public function resizeImage($file, $width, $height)
 {
     if ($template = $this->getTemplate()) {
         $app = JFactory::getApplication();
         $client = JApplicationHelper::getClientInfo($template->client_id);
         $relPath = base64_decode($file);
         $path = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);
         $JImage = new JImage($path);
         try {
             $image = $JImage->resize($width, $height, true, 1);
             $image->toFile($path);
             return true;
         } catch (Exception $e) {
             $app->enqueueMessage($e->getMessage(), 'error');
         }
     }
 }
Exemplo n.º 19
0
 /**
  * Method to get the list of input[type="file"]
  *
  * @return  string  The field input markup.
  *
  * @since   11.1
  */
 protected function getInput()
 {
     $output = '';
     $params = JComponentHelper::getParams('com_jea');
     $imgUploadNumber = $params->get('img_upload_number', 3);
     for ($i = 0; $i < $imgUploadNumber; $i++) {
         $output .= '<input type="file" name="newimages[]" value=""  size="30" class="fltnone" /> <br />';
     }
     $output .= "\n";
     //alert & return if GD library for PHP is not enabled
     if (!extension_loaded('gd')) {
         $output .= '<strong>WARNING: </strong>The <a href="http://php.net/manual/en/book.image.php" target="_blank">GD library for PHP</a> was not found. Ensure to install it';
         return $output;
     }
     if (is_string($this->value)) {
         $images = (array) json_decode($this->value);
     } else {
         $images = (array) $this->value;
         foreach ($images as $k => $image) {
             $images[$k] = (object) $image;
         }
     }
     $propertyId = $this->form->getValue('id');
     $baseURL = JURI::root(true);
     $imgBaseURL = $baseURL . '/images/com_jea/images/' . $propertyId;
     $imgBasePath = JPATH_ROOT . DS . 'images' . DS . 'com_jea' . DS . 'images' . DS . $propertyId;
     if (!empty($images)) {
         $output .= "<ul class=\"gallery\">\n";
         foreach ($images as $k => $image) {
             $imgPath = $imgBasePath . DS . $image->name;
             try {
                 $infos = JImage::getImageFileProperties($imgPath);
             } catch (Exception $e) {
                 $output .= "<li>Recorded Image " . $image->name . " cannot be accessed</li>\n";
                 continue;
             }
             $thumbName = 'thumb-admin-' . $image->name;
             // Create the thumbnail
             if (!file_exists($imgBasePath . DS . $thumbName)) {
                 try {
                     // This is where the JImage will be used, so only create it here
                     $JImage = new JImage($imgPath);
                     $thumb = $JImage->resize(150, 90);
                     $thumb->crop(150, 90, 0, 0);
                     $thumb->toFile($imgBasePath . DS . $thumbName);
                     // To avoid memory overconsumption, destroy the JImage now that we don't need it anymore
                     if (method_exists($JImage, 'destroy')) {
                         $JImage->destroy();
                         $thumb->destroy();
                     } else {
                         // There is no destroy method on Jplatform < 12.3 (Joomla 2.5) and the handle property is protected.
                         // We have to hack the JImage class to destroy the image resource
                         $prop = new ReflectionProperty('JImage', 'handle');
                         $prop->setAccessible(true);
                         $JImageHandle = $prop->getValue($JImage);
                         $thumbHandle = $prop->getValue($thumb);
                         if (is_resource($JImageHandle)) {
                             imagedestroy($JImageHandle);
                         }
                         if (is_resource($thumbHandle)) {
                             imagedestroy($thumbHandle);
                         }
                     }
                 } catch (Exception $e) {
                     $output .= "<li>Thumbnail for " . $image->name . " cannot be generated</li>\n";
                     continue;
                 }
             }
             $thumbUrl = $imgBaseURL . '/' . $thumbName;
             $url = $imgBaseURL . '/' . $image->name;
             $weight = round($infos->bits / 1024, 1);
             // Ko
             $output .= "<li class=\"item-{$k}\">\n" . "<a href=\"{$url}\" title=\"Zoom\" class=\"imgLink modal\" rel=\"{handler: 'image'}\"><img src=\"{$thumbUrl}\" alt=\"{$image->name}\" /></a>\n" . "<div class=\"imgInfos\">\n" . $image->name . "<br />\n" . JText::_('COM_JEA_WIDTH') . ' : ' . $infos->width . ' px' . "<br />\n" . JText::_('COM_JEA_HEIGHT') . ' : ' . $infos->height . ' px' . "<br />\n" . "</div>\n" . "<div class=\"imgTools\">\n" . '  <a class="img-move-up" title="' . JText::_('JLIB_HTML_MOVE_UP') . '"><img src="' . $baseURL . '/media/com_jea/images/sort_asc.png' . '" alt="Move up" /></a>' . '  <a class="img-move-down" title="' . JText::_('JLIB_HTML_MOVE_DOWN') . '"><img src="' . $baseURL . '/media/com_jea/images/sort_desc.png' . '" alt="Move down" /></a>' . '  <a class="delete-img" title="' . JText::_('JACTION_DELETE') . '"><img src="' . $baseURL . '/media/com_jea/images/media_trash.png' . '" alt="Delete" /></a>' . "</div>\n" . "<div class=\"clr\"></div>\n" . '<label for="' . $this->id . $k . 'title">' . JText::_('JGLOBAL_TITLE') . '</label><input id="' . $this->id . $k . 'title" type="text" name="' . $this->name . '[' . $k . '][title]" value="' . $image->title . '" size="20"/><br />' . '<label for="' . $this->id . $k . 'desc">' . JText::_('JGLOBAL_DESCRIPTION') . '</label><input id="' . $this->id . $k . 'desc" type="text" name="' . $this->name . '[' . $k . '][description]" value="' . $image->description . '" size="40"/>' . '<input type="hidden" name="' . $this->name . '[' . $k . '][name]" value="' . $image->name . '" />' . "<div class=\"clr\"></div>\n" . "</li>\n";
         }
         $output .= "</ul>\n";
         // Add javascript behavior
         JHtml::_('behavior.modal');
         JFactory::getDocument()->addScriptDeclaration("\n                window.addEvent('domready', function() {\n                    var sortOptions = {\n                        transition: Fx.Transitions.Back.easeInOut,\n                        duration: 700,\n                        mode: 'vertical',\n                        onComplete: function() {\n                           mySort.rearrangeDOM()\n                        }\n                    };\n\n                    var mySort = new Fx.Sort(\$\$('ul.gallery li'), sortOptions);\n\n                    \$\$('a.delete-img').each(function(item) {\n                        item.addEvent('click', function() {\n                            this.getParent('li').destroy();\n                            mySort = new Fx.Sort(\$\$('ul.gallery li'), sortOptions);\n                        });\n                    });\n\n                    \$\$('a.img-move-up').each(function(item) {\n                        item.addEvent('click', function() {\n                            var activeLi = this.getParent('li');\n                            if (activeLi.getPrevious()) {\n                                mySort.swap(activeLi, activeLi.getPrevious());\n                            } else if (this.getParent('ul').getChildren().length > 1 ) {\n                                // Swap with the last element\n                            \tmySort.swap(activeLi, this.getParent('ul').getLast('li'));\n                            }\n                        });\n                    });\n\n                     \$\$('a.img-move-down').each(function(item) {\n                        item.addEvent('click', function() {\n                            var activeLi = this.getParent('li');\n                            if (activeLi.getNext()) {\n                                mySort.swap(activeLi, activeLi.getNext());\n                            } else if (this.getParent('ul').getChildren().length > 1 ) {\n                                // Swap with the first element\n                            \tmySort.swap(activeLi, this.getParent('ul').getFirst('li'));\n                            }\n                        });\n                    });\n\n                })");
     }
     return $output;
 }
Exemplo n.º 20
0
 $imageinfo = getimagesize($image['tmp_name']);
 $mime_types = $sconfig->mime_types;
 $okMIMETypes = $mime_types;
 $validFileTypes = explode(",", $okMIMETypes);
 if (is_int($imageinfo[0]) || is_int($imageinfo[1]) || in_array($imageinfo['mime'], $validFileTypes)) {
     $image['name'] = preg_replace("/[^A-Za-z.0-9]/i", "-", $image['name']);
     $newName = 'profile-' . $uid . '-' . $time . '-' . $image['name'];
     $newName2 = 'profile-x-' . $uid . '-' . $time . '-' . $image['name'];
     $uploadPath = $base_path . $uid . DS . $newName;
     $uploadPath2 = $base_path . $uid . DS . $newName2;
     $file_name = $newName2;
     JFile::upload($image['tmp_name'], $uploadPath);
     ####################
     $image = new JImage($uploadPath);
     $properties = JImage::getImageFileProperties($uploadPath);
     $resizedImage = $image->resize('400', '300', true);
     $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($uploadPath, $type);
     watermark_image($uploadPath, $uploadPath2, $mime);
     ####################
     ######adaugare in baza de date
     $upd_poza = ", `poza` = '" . $file_name . "'";
     //verificam daca avem poza
     $query = "SELECT `poza` FROM #__sa_profiles WHERE `uid` = '" . $uid . "'";
Exemplo n.º 21
0
 /**
  * Crop the image and generates smaller ones.
  *
  * @param string $file
  * @param array $options
  *
  * @throws Exception
  *
  * @return array
  */
 public function cropImage($file, $options)
 {
     // Resize image
     $image = new JImage();
     $image->loadFile($file);
     if (!$image->isLoaded()) {
         throw new Exception(JText::sprintf('COM_CROWDFUNDING_ERROR_FILE_NOT_FOUND', $file));
     }
     $destinationFolder = Joomla\Utilities\ArrayHelper::getValue($options, "destination");
     // Generate temporary file name
     $generatedName = new Prism\String();
     $generatedName->generateRandomString(32);
     $imageName = $generatedName . "_image.png";
     $smallName = $generatedName . "_small.png";
     $squareName = $generatedName . "_square.png";
     $imageFile = $destinationFolder . DIRECTORY_SEPARATOR . $imageName;
     $smallFile = $destinationFolder . DIRECTORY_SEPARATOR . $smallName;
     $squareFile = $destinationFolder . DIRECTORY_SEPARATOR . $squareName;
     // Create main image
     $width = Joomla\Utilities\ArrayHelper::getValue($options, "width", 200);
     $width = $width < 25 ? 50 : $width;
     $height = Joomla\Utilities\ArrayHelper::getValue($options, "height", 200);
     $height = $height < 25 ? 50 : $height;
     $left = Joomla\Utilities\ArrayHelper::getValue($options, "x", 0);
     $top = Joomla\Utilities\ArrayHelper::getValue($options, "y", 0);
     $image->crop($width, $height, $left, $top, false);
     // Resize to general size.
     $width = Joomla\Utilities\ArrayHelper::getValue($options, "resize_width", 200);
     $width = $width < 25 ? 50 : $width;
     $height = Joomla\Utilities\ArrayHelper::getValue($options, "resize_height", 200);
     $height = $height < 25 ? 50 : $height;
     $image->resize($width, $height, false);
     // Store to file.
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Load parameters.
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     // Create small image
     $width = $params->get("image_small_width", 100);
     $height = $params->get("image_small_height", 100);
     $image->resize($width, $height, false);
     $image->toFile($smallFile, IMAGETYPE_PNG);
     // Create square image
     $width = $params->get("image_square_width", 50);
     $height = $params->get("image_square_height", 50);
     $image->resize($width, $height, false);
     $image->toFile($squareFile, IMAGETYPE_PNG);
     $names = array("image" => $imageName, "image_small" => $smallName, "image_square" => $squareName);
     // Remove the temporary file.
     if (is_file($file)) {
         JFile::delete($file);
     }
     return $names;
 }
Exemplo n.º 22
0
 function onUserAfterSave($data, $isNew, $result, $error)
 {
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $files = JRequest::getVar('jform', null, 'files');
     $post = JRequest::getVar('jform', null);
     /*var_dump($_GET["task"]);
     		var_dump($_POST["task"]);
     		die;*/
     if ($_GET["task"] != "registration.register" && $_POST["task"] != "register") {
         $savedNewProfilePicture = false;
         // Save original picture, resized pictures and save them
         if ($files['error']['profilepicture']['file'] == 0) {
             $profilepicture = new JImage($files['tmp_name']['profilepicture']['file']);
             $sourceWidth = $profilepicture->getWidth();
             $sourceHeight = $profilepicture->getHeight();
             if ($sourceWidth < PROFILEPICTURE_SIZE_200 || $sourceHeight < PROFILEPICTURE_SIZE_200) {
                 throw new Exception(JText::_('PLG_USER_PROFILEPICTURE_ERROR_TOO_SMALL'));
             }
             $pp_filename = sha1($userId . uniqid()) . '.' . plgUserProfilePicture::FILE_EXTENSION;
             foreach ($this->sizes as $size) {
                 if ($size == PROFILEPICTURE_SIZE_ORIGINAL) {
                     $profilepicture->toFile(PROFILEPICTURE_PATH_ORIGINAL . $pp_filename);
                     $savedNewProfilePicture = true;
                 } else {
                     $ratio = max($sourceWidth, $sourceHeight) / $size;
                     $ratio = max($ratio, 1.0);
                     $resizedWidth = (int) ($sourceWidth / $ratio);
                     $resizedHeight = (int) ($sourceHeight / $ratio);
                     $left = 0;
                     $top = 0;
                     if ($this->square && $sourceWidth > $size && $sourceHeight > $size) {
                         if ($sourceWidth > $sourceHeight) {
                             $left = (int) ($sourceWidth - $sourceHeight) / 2;
                             $top = 0;
                             $croppedWidth = $sourceHeight;
                             $croppedHeight = $sourceHeight;
                             $resizedHeight = $resizedWidth;
                         } elseif ($sourceHeight > $sourceWidth) {
                             $left = 0;
                             $top = (int) (($sourceHeight - $sourceWidth) / 2);
                             $croppedWidth = $sourceWidth;
                             $croppedHeight = $sourceWidth;
                             $resizedWidth = $resizedHeight;
                         }
                         $cropped = $profilepicture->crop($croppedWidth, $croppedHeight, $left, $top, true);
                         $resized = $cropped->resize($resizedWidth, $resizedHeight, true, JImage::SCALE_OUTSIDE);
                         $resized->toFile(constant('PROFILEPICTURE_PATH_' . $size) . $pp_filename);
                         $savedNewProfilePicture = true;
                     } else {
                         $resized = $profilepicture->resize($size, $size, true, JImage::SCALE_INSIDE);
                         $resized->toFile(constant('PROFILEPICTURE_PATH_' . $size) . $pp_filename);
                         $savedNewProfilePicture = true;
                     }
                 }
             }
         }
         // Remove profile picture if an existing profile picture is
         // checked for removal or a new picture has been uploaded
         // replacing the existing picture.
         if (isset($userId) && (!empty($post['profilepicture']['file']['remove']) || $savedNewProfilePicture)) {
             $this->removeProfilePicture($userId);
         }
         if ($userId && $savedNewProfilePicture) {
             try {
                 $db = JFactory::getDbo();
                 $query = $db->getQuery(true);
                 $query = $db->getQuery(true);
                 $query->insert('#__user_profiles')->columns('user_id, profile_key, profile_value, ordering')->values($userId . ', ' . $db->quote(plgUserProfilePicture::PROFILE_KEY) . ', ' . $db->quote($pp_filename) . ', ' . ' 1');
                 $db->setQuery($query);
                 if (!$db->query()) {
                     throw new Exception($db->getErrorMsg());
                 }
             } catch (JException $e) {
                 $this->_subject->setError($e->getMessage());
                 return false;
             }
         }
         return true;
     } else {
         return true;
     }
 }
Exemplo n.º 23
0
 /**
  * Метод для генерации изображения
  * @param string $url    УРЛ изображения
  * @param string $file_output    Название изображения для сохранения
  * @param int $w_o, $h_o    Максимальные ширина и высота генерируемого изображения
  * @return string    Результат выполнения false - изображения нет, up - успешно записали и нужно обновиться, ok - изображение существует и не требует модификации
  */
 private function createAvatar($file_input, $file_output, $width, $height)
 {
     //Если источник не указан
     if (!$file_input) {
         return false;
     }
     //папка для работы с изображением и качество сжатия
     $rootfolder = $this->params->get('rootfolder', 'images/avatar');
     $img_quality = $this->params->get('img_quality', 80);
     //если папка для складирования аватаров не существует создаем ее
     if (!JFolder::exists(JPATH_ROOT . '/' . $rootfolder)) {
         JFolder::create(JPATH_ROOT . '/' . $rootfolder);
         file_put_contents(JPATH_ROOT . '/' . $rootfolder . '/index.html', '');
     }
     // Генерируем имя tmp-изображения
     $tmp_name = JPATH_ROOT . '/tmp/' . $file_output;
     $output_path = JPATH_ROOT . '/' . $rootfolder . '/';
     $output_name = $output_path . $file_output;
     //заузка файла
     $uploaded = $this->upload($file_input, $tmp_name);
     if ($uploaded) {
         $image = new JImage($tmp_name);
         $image->resize($width, $height, false, JImage::SCALE_INSIDE);
         $image->toFile($output_name, IMAGETYPE_JPEG, array('quality' => $img_quality));
         unlink($tmp_name);
     }
     $ret = JFile::exists($output_name) ? true : false;
     return $ret;
 }
Exemplo n.º 24
0
 /**
  * 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;
 }
Exemplo n.º 25
0
 /**
  * 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;
 }
Exemplo n.º 26
0
 function onUserAfterSave($data, $isNew, $result, $error)
 {
     $userId = JArrayHelper::getValue($data, 'id', 0, 'int');
     $files = JRequest::getVar('jform', null, 'files');
     $post = JRequest::getVar('jform', null);
     $savedNewProfileCover = false;
     // Save original cover, resized covers and save them
     if ($files['error']['profilecover']['file'] == 0 && !empty($files['tmp_name']['profilecover']['file'])) {
         // Throw new exception if the uploaded file exceed the maximum allowed file size.
         if ($this->doesExceedFileSizeLimit($files['size']['profilecover']['file'])) {
             throw new Exception(JText::sprintf('PLG_USER_PROFILECOVER_ERROR_FILE_SIZE_TOO_BIG', $this->maxUploadSizeInBytes() / 1000));
         }
         $profilecover = new JImage($files['tmp_name']['profilecover']['file']);
         $sourceWidth = $profilecover->getWidth();
         $sourceHeight = $profilecover->getHeight();
         if ($sourceWidth < PROFILECOVER_SIZE_200 || $sourceHeight < PROFILECOVER_SIZE_200) {
             throw new Exception(JText::_('PLG_USER_PROFILECOVER_ERROR_TOO_SMALL'));
         }
         $pp_filename = sha1($userId . uniqid()) . '.' . plgUserProfileCover::FILE_EXTENSION;
         foreach ($this->sizes as $size) {
             if ($size == PROFILECOVER_SIZE_ORIGINAL) {
                 $profilecover->toFile(PROFILECOVER_PATH_ORIGINAL . $pp_filename);
                 $savedNewProfileCover = true;
             } else {
                 $ratio = max($sourceWidth, $sourceHeight) / $size;
                 $ratio = max($ratio, 1.0);
                 $resizedWidth = (int) ($sourceWidth / $ratio);
                 $resizedHeight = (int) ($sourceHeight / $ratio);
                 $left = 0;
                 $top = 0;
                 if ($this->square && $sourceWidth > $size && $sourceHeight > $size) {
                     if ($sourceWidth > $sourceHeight) {
                         $left = (int) ($sourceWidth - $sourceHeight) / 2;
                         $top = 0;
                         $croppedWidth = $sourceHeight;
                         $croppedHeight = $sourceHeight;
                         $resizedHeight = $resizedWidth;
                     } elseif ($sourceHeight >= $sourceWidth) {
                         $left = 0;
                         $top = (int) (($sourceHeight - $sourceWidth) / 2);
                         $croppedWidth = $sourceWidth;
                         $croppedHeight = $sourceWidth;
                         $resizedWidth = $resizedHeight;
                     }
                     $cropped = $profilecover->crop($croppedWidth, $croppedHeight, $left, $top, true);
                     $resized = $cropped->resize($resizedWidth, $resizedHeight, true, JImage::SCALE_OUTSIDE);
                     $resized->toFile(constant('PROFILECOVER_PATH_' . $size) . $pp_filename);
                     $savedNewProfileCover = true;
                 } else {
                     $resized = $profilecover->resize($size, $size, true, JImage::SCALE_INSIDE);
                     $resized->toFile(constant('PROFILECOVER_PATH_' . $size) . $pp_filename);
                     $savedNewProfileCover = true;
                 }
             }
         }
     }
     // Remove profile cover if an existing profile cover is
     // checked for removal or a new cover has been uploaded
     // replacing the existing cover.
     if (isset($userId) && (!empty($post['profilecover']['file']['remove']) || $savedNewProfileCover)) {
         $this->removeProfileCover($userId);
     }
     if ($userId && $savedNewProfileCover) {
         try {
             $db = JFactory::getDbo();
             $query = $db->getQuery(true);
             $query = $db->getQuery(true);
             $query->insert('#__user_profiles')->columns('user_id, profile_key, profile_value, ordering')->values($userId . ', ' . $db->quote(plgUserProfileCover::PROFILE_KEY) . ', ' . $db->quote($pp_filename) . ', ' . ' 1');
             $db->setQuery($query);
             if (!$db->query()) {
                 throw new Exception($db->getErrorMsg());
             }
         } catch (JException $e) {
             $this->_subject->setError($e->getMessage());
             return false;
         }
     }
     return true;
 }
Exemplo n.º 27
0
 public function resizeImage($src, $gallery = null, $dest = null)
 {
     if ($src) {
         $type = JFile::getExt($src);
         $org_file = str_replace('.' . $type, '_o.' . $type, $src);
         $params = $this->getState('params');
         $sizes = $this->getState('sizeImage');
         if ($gallery) {
             $sizes = $this->getState('size');
         }
         if (!JFile::exists($org_file)) {
             $this->setError(JText::_('COM_TZ_PORTFOLIO_IMAGE_FILE_DOES_NOT_EXIST'));
             return false;
         }
         $dest_path = $dest;
         if ($sizes) {
             $image = new JImage($org_file);
             $width = $image->getWidth();
             $height = $image->getHeight();
             // Resize images
             foreach ($sizes as $key => $newWidth) {
                 $newHeight = $height * $newWidth / $width;
                 $newImage = $image->resize($newWidth, $newHeight);
                 if (!$dest) {
                     $dest_path = str_replace('.' . $type, '_' . $key . '.' . $type, $src);
                 }
                 if (JFile::exists($dest_path)) {
                     JFile::delete($dest_path);
                 }
                 $newImage->toFile($dest_path, $this->_getImageType($src));
             }
             return true;
         }
         return false;
     }
     return false;
 }
Exemplo n.º 28
0
 function uploadLocal()
 {
     $img = $_FILES['upload_pinl'];
     $arr = array('image/jpeg', 'image/jpg', 'image/bmp', 'image/gif', 'image/png', 'image/ico');
     $maxSize = 10 * 1024 * 1024;
     $erro = array();
     $size_img = $this->getState('size_img');
     $tzFolderPath = JPATH_ROOT . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'tz_pinboard' . DIRECTORY_SEPARATOR . 'article' . DIRECTORY_SEPARATOR . 'cache';
     if (!JFolder::exists($tzFolderPath)) {
         JFolder::create($tzFolderPath);
     }
     $check_file_type = in_array(strtolower($img['type']), $arr);
     if ($check_file_type == false) {
         $erro[] = "incorrect file type";
     }
     if ($img['size'] > $maxSize) {
         $erro[] = "file too large";
     }
     $_erro = count($erro);
     if ($_erro == '0') {
         $FileName_img = 'Pin_' . time() . uniqid() . '.' . str_replace('image/', '', $img['type']);
         $_FILES['upload_pinl']['name'] = $FileName_img;
         $type = $this->_getImageType($FileName_img);
         if ($type == 1) {
             $uploadfile = $tzFolderPath . '/' . basename($_FILES['upload_pinl']['name']);
             move_uploaded_file($_FILES['upload_pinl']['tmp_name'], $uploadfile);
             $desttamp = $tzFolderPath . DIRECTORY_SEPARATOR . $FileName_img;
             preg_match('/media.*?$/', $desttamp, $path_img);
             return $path_img1 = str_replace('\\', '/', $path_img[0]);
         } else {
             $desttamp = $tzFolderPath . DIRECTORY_SEPARATOR . $FileName_img;
             $obj = new JImage($img['tmp_name']);
             $width = $obj->getWidth();
             $height = $obj->getHeight();
             $arr_upload = array();
             foreach ($size_img as $key => $newWidth) {
                 $destPath = $tzFolderPath . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $FileName_img);
                 $destPath = str_replace('.' . JFile::getExt($destPath), '_' . $key . '.' . JFile::getExt($destPath), $destPath);
                 $newHeight = $height * (int) $newWidth / $width;
                 $newImage = $obj->resize($newWidth, $newHeight, true);
                 $arr_upload[] = $newImage->toFile($destPath, $type);
             }
             if ($arr_upload[0] == true) {
                 preg_match('/media.*?$/', $desttamp, $path_img);
                 return $path_img1 = str_replace('\\', '/', $path_img[0]);
             } else {
                 return false;
             }
         }
     } else {
         return false;
     }
 }
Exemplo n.º 29
-1
 /**
  * Upload an image
  *
  * @param  array $image
  * @param  string $destination
  *
  * @throws Exception
  * @return array
  */
 public function uploadImage($image, $destination)
 {
     $app = JFactory::getApplication();
     /** @var $app JApplicationSite */
     $uploadedFile = Joomla\Utilities\ArrayHelper::getValue($image, 'tmp_name');
     $uploadedName = Joomla\Utilities\ArrayHelper::getValue($image, 'name');
     $errorCode = Joomla\Utilities\ArrayHelper::getValue($image, 'error');
     // Load parameters.
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     $tmpFolder = $app->get('tmp_path');
     // Joomla! media extension parameters
     $mediaParams = JComponentHelper::getParams('com_media');
     /** @var  $mediaParams Joomla\Registry\Registry */
     $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;
     $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 = JString::strtolower(JFile::makeSafe(JFile::getExt($image['name'])));
     $generatedName = Prism\Utilities\StringHelper::generateRandomString(32);
     $tmpDestFile = JPath::clean($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
     $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 = $destination . DIRECTORY_SEPARATOR . $imageName;
     // Get the scale method.
     $scaleMethod = $params->get('image_resizing_scale', JImage::SCALE_INSIDE);
     // Create main image
     $width = $params->get('pitch_image_width', 600);
     $height = $params->get('pitch_image_height', 400);
     $image->resize($width, $height, false, $scaleMethod);
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Remove the temporary file.
     if (is_file($tmpDestFile)) {
         JFile::delete($tmpDestFile);
     }
     return $imageName;
 }
Exemplo n.º 30
-1
 /**
  * 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');
     $params = JComponentHelper::getParams($this->option);
     /** @var  $params Joomla\Registry\Registry */
     $temporaryFolder = JPath::clean($app->get('tmp_path'));
     // Joomla! media extension parameters
     /** @var  $mediaParams Joomla\Registry\Registry */
     $mediaParams = JComponentHelper::getParams('com_media');
     $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);
     // 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 = Prism\Utilities\StringHelper::generateRandomString(16);
     $originalFile = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $generatedName . '.' . $ext);
     if (!JFile::upload($uploadedFile, $originalFile)) {
         throw new \RuntimeException(\JText::_('COM_SOCIALCOMMUNITY_ERROR_FILE_CANT_BE_UPLOADED'));
     }
     // Generate file names for the image files.
     $generatedName = Prism\Utilities\StringHelper::generateRandomString(16);
     $imageName = $generatedName . '_image.png';
     $smallName = $generatedName . '_small.png';
     $squareName = $generatedName . '_square.png';
     $iconName = $generatedName . '_icon.png';
     // Resize image
     $image = new JImage();
     $image->loadFile($originalFile);
     if (!$image->isLoaded()) {
         throw new RuntimeException(JText::sprintf('COM_SOCIALCOMMUNITY_ERROR_FILE_NOT_FOUND', $originalFile));
     }
     $imageFile = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $imageName);
     $smallFile = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $smallName);
     $squareFile = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $squareName);
     $iconFile = JPath::clean($temporaryFolder . DIRECTORY_SEPARATOR . $iconName);
     // Create profile picture
     $width = $params->get('image_width', 200);
     $height = $params->get('image_height', 200);
     $image->resize($width, $height, false);
     $image->toFile($imageFile, IMAGETYPE_PNG);
     // Create small profile picture
     $width = $params->get('small_width', 100);
     $height = $params->get('small_height', 100);
     $image->resize($width, $height, false);
     $image->toFile($smallFile, IMAGETYPE_PNG);
     // Create square picture
     $width = $params->get('square_width', 50);
     $height = $params->get('square_height', 50);
     $image->resize($width, $height, false);
     $image->toFile($squareFile, IMAGETYPE_PNG);
     // Create icon picture
     $width = $params->get('icon_width', 24);
     $height = $params->get('icon_height', 24);
     $image->resize($width, $height, false);
     $image->toFile($iconFile, IMAGETYPE_PNG);
     // Remove the temporary file
     if (JFile::exists($originalFile)) {
         JFile::delete($originalFile);
     }
     return $names = array('image' => $imageName, 'image_small' => $smallName, 'image_icon' => $iconName, 'image_square' => $squareName);
 }