Jump to content

Recommended Posts

Hi,

 

Having trouble implementing an image resizer script:

 

<?php
// Create image from file
switch(strtolower($_FILES['Filedata']['type']))
{
case 'image/jpeg':
 $image = imagecreatefromjpeg($_FILES['Filedata']['tmp_name']);
 break;
case 'image/png':
 $image = imagecreatefrompng($_FILES['Filedata']['tmp_name']);
 break;
case 'image/gif':
 $image = imagecreatefromgif($_FILES['Filedata']['tmp_name']);
 break;
}
// Target dimensions
$max_width = 240;
$max_height = 180;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale	 = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);

// Catch the imagedata
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
?>

 

 

 

 

 

 

to the following upload script:

 

<?php
/* *
    * upload avatar
    */
   function uploadavatar()
   {
       $app = JFactory::getApplication();

       $db = JFactory::getDBO();
       $user =  JFactory::getUser();        

       // load language for component media
       JPlugin::loadLanguage( 'com_media', JPATH_SITE );
       JPlugin::loadLanguage( 'com_media', JPATH_ADMINISTRATOR );

       $params = JComponentHelper::getParams('com_media');

       require_once( JPATH_SITE.DS.'components'.DS.'com_media'.DS.'helpers'.DS.'media.php' );

       define('COM_AUP_MEDIA_BASE_IMAGE', JPATH_ROOT.DS.'components'.DS.'com_alphauserpoints'.DS.'assets'.DS.'images');        

       // Check for request forgeries
       JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );

       $file         = JRequest::getVar( 'Filedata', '', 'files', 'array' );
       $folder        = JRequest::getVar( 'folder', 'avatars', '', 'path' );
       $format        = JRequest::getVar( 'format', 'html', '', 'cmd');
       $return        = JRequest::getVar( 'return-url', null, 'post', 'base64' );
       $referrerid = JRequest::getVar( 'referrerid', '', 'post', 'string' );
       $err        = null;

       // Set FTP credentials, if given
       jimport('joomla.client.helper');
       JClientHelper::setCredentialsFromRequest('ftp');

       // Make the filename safe
       jimport('joomla.filesystem.file');
       $file['name'] = JFile::makeSafe($file['name']);

       if (isset($file['name']) && $referrerid!='') {
           $extention = JFile::getExt($file['name']);
           $newnameavatar = strtolower($referrerid.'.'.$extention);

           //chmod (COM_AUP_MEDIA_BASE_IMAGE.DS.$folder, 0755) ;
           $filepath = JPath::clean(COM_AUP_MEDIA_BASE_IMAGE.DS.$folder.DS.$newnameavatar);
           // erase old avatar
           if ( file_exists($filepath) ) @unlink( $filepath );

           if (!MediaHelper::canUpload( $file, $err )) {
               if ($format == 'json') {
                   jimport('joomla.error.log');
                   $log = JLog::getInstance('upload.error.php');
                   $log->addEntry(array('comment' => 'Invalid: '.$filepath.': '.$err));
                   header('HTTP/1.0 415 Unsupported Media Type');
                   jexit('Error. Unsupported Media Type!');
               } else {
                   JError::raiseNotice(100, JText::_($err));
                   // REDIRECT
                   if ($return) {
                       $app->redirect(base64_decode($return));
                   }
                   return;
               }
           }

           if (JFile::exists($filepath)) {
               if ($format == 'json') {
                   jimport('joomla.error.log');
                   $log = JLog::getInstance('upload.error.php');
                   $log->addEntry(array('comment' => 'File already exists: '.$filepath));
                   header('HTTP/1.0 409 Conflict');
                   jexit('Error. File already exists');
               } else {
                   JError::raiseNotice(100, JText::_('UPLOAD FAILED. FILE ALREADY EXISTS'));
                   // REDIRECT
                   if ($return) {
                       $app->redirect(base64_decode($return));
                   }
                   return;
               }
           }

           if (!JFile::upload($file['tmp_name'], $filepath)) {
               if ($format == 'json') {
                   jimport('joomla.error.log');
                   $log = JLog::getInstance('upload.error.php');
                   $log->addEntry(array('comment' => 'Cannot upload: '.$filepath));
                   header('HTTP/1.0 400 Bad Request');
                   jexit('ERROR. UNABLE TO UPLOAD FILE');
               } else {
                   JError::raiseWarning(100, JText::_('ERROR. UNABLE TO UPLOAD FILE'));
                   // REDIRECT
                   if ($return) {
                       $app->redirect(base64_decode($return));
                   }
                   return;
               }
           } else {
               // SAVE IN PROFIL USER ALPHAUSERPOINTS
               $query = "UPDATE #__alpha_userpoints" .
               "\n SET avatar='".$newnameavatar."'" .
               "\n WHERE referreid='".$referrerid."' AND userid='" . $user->id . "'"
               ;
               $db->setQuery( $query );            
               if (!$db->query())
               {
                   JError::raiseError( 500, $db->getErrorMsg() );            
                   return false;
               }

               require_once (JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php');

               if ($format == 'json') {
                   jimport('joomla.error.log');
                   $log = JLog::getInstance();
                   $log->addEntry(array('comment' => $folder));
                   jexit('Upload complete');
                   // apply rule for upload avatar
                   AlphaUserPointsHelper::userpoints( 'sysplgaup_uploadavatar', '', 0, $referrerid );

               } else {
                   $app->enqueueMessage(JText::_('UPLOAD COMPLETE'));

                   // apply rule for upload avatar
                   AlphaUserPointsHelper::userpoints( 'sysplgaup_uploadavatar', '', 0, $referrerid );

                   // REDIRECT
                   if ($return) {
                       $app->redirect(base64_decode($return));
                   }
                   return;
               }
           }
       } else {
           $app->redirect('index.php', 'Invalid Request', 'error');
       }
   }

}
?>

 

I'm still new to PHP and I'm learning, so any help would be appreciated.

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/271167-image-resizer-for-upload-system/
Share on other sites

I attempted to replace the $file string with $image, but had no luck. I think that the problem might be that the this:

$file = JRequest::getVar( 'Filedata', '', 'files', 'array' );

Does not get the same data as this:

$_FILES['Filedata']

Which is why I may be having problems.

But the conversion script itself will work on its own and get the image data, resize and return the image, the problem is implementing it with the current script.

 

If I do replace this:

$file = $_FILES['Filedata']

With this:

$file = JRequest::getVar( 'Filedata', '', 'files', 'array' );

Will it be retrieving the same image data?

 

I can usually work out a lot of this sort of stuff, although it takes me a while, but this one has me stuck.

I'm not at the level yet where I can just know how to make it work, I have to do this by trial and error and through research and examples, it's difficult.

 

I tried placing the following under the check for forgeries comment and getting rid of the $file = .... And then changing the rest of the $file strings to $newfile, but no luck, it either returns an error or ignores the resize script, depending if I delete the $file =... etc.

 

// Target dimensions
$max_width = 240;
$max_height = 180;
// Get current dimensions
$old_width = imagesx($file);
$old_height = imagesy($file);
// Calculate the scaling we need to do to fit the image inside our frame
$scale   = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, file,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
// Catch the imagedata
ob_start();
imagejpeg($new, NULL, 90);
$filenew = ob_get_clean();
// Destroy resources
imagedestroy($file);
imagedestroy($new);

 

Sorry for my lack of articulation, I can answer questions to the best of my knowledge if you are willing to ask them.

Thanks.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.