Resizing an image on upload

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

Resizing an image on upload

Post by bla5e »

I made an image uploader, but the client doesnt want the users to have to manually change the height & width (50x50px), he wants it done upon upload. Anyone have a simple block of code todo this? Here is what I got so far..

Code: Select all

if ($_FILES['upload'] != ''){
    if ( (($_FILES['upload']['type'] == 'image/gif') || ($_FILES['upload']['type'] == 'image/png') || ($_FILES['upload']['type'] == 'image/jpeg') || ($_FILE\
S['upload']['type'] == 'image/pjpeg')) && ($_FILES["file"]["size"] < 50000)){
      if($_FILES['upload']['error'] > 0){
        $smarty->assign('error', 'Return Code: '.$_FILES['upload']['error'].'');
      } else {                                                                                                                                      
        if (file_exists("../images/editors/" . $_FILES['upload']['name'])) {
          $smarty->assign('error', 'The file you tried to upload ('.$_FILES['upload']['name'].') already exists. ');
        } else {
          //IMAGE RESIZE BLOCK SHOULD GO IN HERE BEFORE MOVING TO SAVED DIRECTORY
          //JUST NOT SURE HOW TO DO IT
          //ALL HELP IS APPRECIATED! :)
          if (!move_uploaded_file($_FILES['upload']['tmp_name'], '../images/editors/'.$_FILES['upload']['name'])){
            $smarty->assign('error', 'Error moving the file.');
          } else {
            $smarty->assign('notice', 'Stored in: images/editors/'.$_FILES['upload']['name'].'');
          }
        }
      }
      $profile_image = $_FILES['upload']['name'];
    } else {
      $smarty->assign('error', 'Invalid file. File must be an image (.jpg, .jpeg, .png, .gif).');
    }
  }
I commented out where I believe the resize should go. Thanks guys, this place is honestly the best place togo for any answers (besides google..)
lunarnet76
Forum Commoner
Posts: 67
Joined: Sun Apr 04, 2010 2:07 pm
Location: Edinburgh

Re: Resizing an image on upload

Post by lunarnet76 »

hi,

first you can resize your image only after move_uploaded_file so the code of resize should go in the else block.

After resizing an image ask to use the GD library of PHP (it's an extension). You can find some script for resize on internet^^
bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

Re: Resizing an image on upload

Post by bla5e »

Ah! does anyone have a quick snippet i can use for reference? dont need a whole script just the most basic means to resize to 50x50
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Resizing an image on upload

Post by Jonah Bron »

bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

Re: Resizing an image on upload

Post by bla5e »

I am probably doing this wrong but i am lost and need some help..

heres is my function to resize the image

Code: Select all

function resize_jpg($inputFilename, $new_side){
  echo '<script type="text/javascript"> alert(\'TEST!\');</script>'; //used for debugging making sure function was being called.
  $imagedata = getimagesize($inputFilename);
  $w = $imagedata[0];
  $h = $imagedata[1];

  if ($h > $w) {
    $new_w = ($new_side / $h) * $w;
    $new_h = $new_side;
  } else {
    $new_h = ($new_side / $w) * $h;
    $new_w = $new_side;
  }

  $im2 = ImageCreateTrueColor($new_w, $new_h);
  $image = ImageCreateFromJpeg('50_'.$inputFilename);
  imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $imagedata[0], $imagedata[1]);
  return $im2;
}
and here is my image uploader script with the image resize applied to it but not resizing the image :(

Code: Select all

if ($_FILES['upload'] != ''){
    if ( (($_FILES['upload']['type'] == 'image/gif') || ($_FILES['upload']['type'] == 'image/png') || ($_FILES['upload']['type'] == 'image/jpeg') || ($_FILE\
S['upload']['type'] == 'image/pjpeg')) && ($_FILES["file"]["size"] < 50000)){
      if($_FILES['upload']['error'] > 0){
        $smarty->assign('error', 'Return Code: '.$_FILES['upload']['error'].'');
      } else {
        //echo 'Upload: '. $_FILES['upload']['name'] .'<br />';                                                                                              
        echo 'Type: '. $_FILES['upload']['type'] .'<br />';
        //echo 'Size: '. ($_FILES['upload']['size'] / 1024) .' Kb<br />';                                                                                    
        //echo 'Temp file: '. $_FILES['upload']['tmp_name'] .'<br />';                                                                                       

        if (file_exists("../images/editors/" . $_FILES['upload']['name'])) {
          $smarty->assign('error', 'The file you tried to upload ('.$_FILES['upload']['name'].') already exists. ');
        } else {
          if (!move_uploaded_file($_FILES['upload']['tmp_name'], '../images/editors/'.$_FILES['upload']['name'])){
            $smarty->assign('error', 'Error moving the file.');
          } else {
            resize_jpg('../images/editors/'.$_FILES['upload']['name'], 50);
            $smarty->assign('notice', 'Stored in: images/editors/'.$_FILES['upload']['name'].'');
          }
        }
      }
      $profile_image = $_FILES['upload']['name'];
    } else {
    $smarty->assign('error', 'Invalid file. File must be an image (.jpg, .jpeg, .png, .gif).');
    }
  }
Not getting any errors, it just uploads the original file without resizing it.
bla5e
Forum Contributor
Posts: 234
Joined: Tue May 25, 2004 4:28 pm

Re: Resizing an image on upload

Post by bla5e »

Got this to work, might even be better idea.. doesnt actually resize the image, just takes current height/width of image and then takes the ratio and exports the HTML with the proper ratio for 50x50.

function

Code: Select all

function resize_image($image,$target) {
  // Get the current image size                                                                                                                              
  $image = getimagesize($image);
  // Get the percentage to resize the image                                                                                                                  
  if ($image[0] > $image[1]) {
    $percent = $target / $image[0];
  } else  {
    $percent = $target / $image[1];
  }
  // Get the new width and height                                                                                                                            
  $w = round($image[0] * $percent);
  $h = round($image[1] * $percent);
  // Return as an html widht/height attribute                                                                                                                
  $htmlWH = "width=\"" . $w . "\" height=\"" . $h . "\"";
  return $htmlWH;
}

Code

Code: Select all

echo '<img src="/images/editors/'.$_FILES['upload']['name'].'" '.resize_image('../images/editors/'.$_FILES['upload']['name'], 50).'>';
Only thing that sucks about this, i need these images to work on multiple pages. I would really like a script that resizes the image on upload (50x50), and deletes the original uploaded image.

Would love a better idea.. but cant think of any other way todo it.
Post Reply