function upload_image() { $user = JFactory::getUser(); JFactory::getDocument()->setMimeEncoding('application/json'); if ($user->guest) { echo json_encode(array('error' => 'no permissions')); return JFactory::getApplication()->close(); } jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); $file = JRequest::getVar('Filedata', '', 'files', 'array'); $extension = JRequest::getVar('extension', null); //mime_content_type() if (($imginfo = getimagesize($file['tmp_name'])) === false) { echo json_encode(array('error' => 'not an image')); return JFactory::getApplication()->close(); } $params = JComponentHelper::getParams('com_media'); $allowed_mime = explode(',', $params->get('upload_mime')); $illegal_mime = explode(',', $params->get('upload_mime_illegal')); if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); $type = finfo_file($finfo, $file['tmp_name']); if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { echo json_encode(array('error' => 'dont try to f**k the server')); return JFactory::getApplication()->close(); } finfo_close($finfo); } elseif (function_exists('mime_content_type')) { $type = mime_content_type($file['tmp_name']); if (strlen($type) && !in_array($type, $allowed_mime) && in_array($type, $illegal_mime)) { echo json_encode(array('error' => 'COM_KSM_ERROR_WARNINVALID_MIME')); return JFactory::getApplication()->close(); } } elseif (!$user->authorise('core.manage')) { echo json_encode(array('error' => 'COM_KSM_ERROR_WARNNOTADMIN')); return JFactory::getApplication()->close(); } $to = JRequest::getString('to', ''); $folder = JRequest::getString('folder', ''); $path = JPATH_ROOT; $to = explode("/", $to); foreach ($to as $s) { $path = $path . DS . $s; if (!JFolder::exists($path)) { if (!JFolder::create($path)) { echo json_encode(array('error' => 'COM_KSM_ERROR_CREATEDIR')); return JFactory::getApplication()->close(); } } } try { $imageObject = new JImage(); $imageObject->loadFile($file['tmp_name']); } catch (Exception $e) { echo json_encode(array('error' => $e->getMessage())); return JFactory::getApplication()->close(); } $pathinfo = pathinfo($file['name']); $fileName = $path . DS . microtime(true) . '.' . $pathinfo['extension']; try { $imageObject->toFile($fileName, IMAGETYPE_JPEG, array('quality', 100)); //$imageObject->save($fileName, 100); } catch (Exception $e) { echo json_encode(array('error' => $e->getMessage())); return JFactory::getApplication()->close(); } $url = KSMedia::resizeImage(basename($fileName), $folder, null, null, null, $extension); $model = $this->getModel('media'); $model->form = 'images'; $item = new stdClass(); $table = $model->getTable('Files'); $table->media_type = 'images'; $table->filename = str_replace(JPATH_ROOT, '', $fileName); $table->folder = $folder; $table->id = '{id}'; $item->images = array(0 => $table); $form = $model->getForm(); $form->setFieldAttribute('images', 'extension', $extension); $form->bind($item); $html = $form->getInput('images'); echo json_encode(array('error' => '', 'filename' => str_replace(JPATH_ROOT, '', $fileName), 'url' => $url, 'html' => $html)); JFactory::getApplication()->close(); }
public function onMediaEditorProcess($filePath) { jimport('joomla.filesystem.file'); $image = new JImage($filePath); if ($image->isLoaded() == false) { throw new LogicException('Failed to load image'); } $image->rotate(180, 0, false); $extension = JFile::getExt($filePath); if (in_array($extension, array('png', 'gif'))) { $imageType = $extension; } else { $imageType = 'jpg'; } $image->toFile($filePath, $imageType); }
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; } }
/** * 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; }
/** * 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; }
/** * Метод для генерации изображения * @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; }
/** * 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; }
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; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * 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); }
/** * 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; }
/** * 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); }