Jump to content

Image upload issue using resize function


Recommended Posts

Hi there,On a page where you can upload images to be displayed on website I am using the following code:

define('THUMB_SIZE_W',200);define('THUMB_SIZE_H',200);define('IMG_SIZE_W',490);define('IMG_SIZE_H',490);function resize_image($src, $dst, $width, $height){  if (file_exists($src))  {    $chunks = explode('.', $src);    $ext = $chunks[count($chunks) - 1];    if ($ext == 'jpg' OR $ext == 'JPG')      $orig = imagecreatefromjpeg($src);    elseif ($ext == 'gif' OR $ext == 'GIF')      $orig = imagecreatefromgif($src);    elseif ($ext == 'png' OR $ext == 'PNG')      $orig = imagecreatefrompng($src);    else    {      echo "Unspported extension ({$ext})";      return;    }    $w = imagesx($orig);    $h = imagesy($orig);    // if it needs to be resized    if ($w > $width || $h > $height)    {      // if the width is larger than allowed      if ($w > $width)      {        $ratio = $width / $w; // ratio is max width divided by actual (<1)        $img = imagecreatetruecolor($width, round($h * $ratio));  // height is actual height times ratio (less)        imagecopyresampled($img, $orig, 0, 0, 0, 0, $width, round($h * $ratio), $w, $h);        $orig = $img;        $w = imagesx($orig);        $h = imagesy($orig);      }      // if the height is larger than allowed      if ($h > $height)      {        $ratio = $height / $h;  // ratio is max height divided by actual (<1)        $img2 = imagecreatetruecolor(round($w * $ratio), $height); // width is actual width times ratio (less)        imagecopyresampled($img2, $orig, 0, 0, 0, 0, round($w * $ratio), $height, $w, $h);        $orig = $img2;        $w = imagesx($orig);        $h = imagesy($orig);      }        switch ($ext)      {        case 'jpg':          imagejpeg($orig, $dst);          break;        case 'gif':          imagegif($orig, $dst);          break;        case 'png':          imagepng($orig, $dst);          break;        case 'JPG':          imagejpeg($orig, $dst);          break;        case 'GIF':          imagegif($orig, $dst);          break;        case 'PNG':          imagepng($orig, $dst);          break;      }    }    imagedestroy($orig);  }  else    echo "Error: the source file does not exist ({$src}, {$dst})";}

This is working all fine as long as the image in not much smaller than the specified THUMB_SIZE_H and THUMB_SIZE_W. If they are the file is not moved into the relevant folders. The move happens via

							if (!move_uploaded_file($_FILES[$imgID]['tmp_name'], "../images/main/{$_FILES[$imgID]['name']}"))         		 			$errors[$imgID] = 'The image could not be moved.';        					else        					{          					resize_image("../images/main/{$_FILES[$imgID]['name']}", "../images/main/{$_FILES[$imgID]['name']}", IMG_SIZE_W, IMG_SIZE_H);         		 			resize_image("../images/main/{$_FILES[$imgID]['name']}", "../images/thumb/{$_FILES[$imgID]['name']}", THUMB_SIZE_W, THUMB_SIZE_H);        					}

Is there a better way to write my function or why do I have issues with smaller sizes?Thanks,Son

Link to post
Share on other sites

It looks as though the problem is that the file copy (via the imagejpg(), imagegif() and imagepng() calls) happens inside the if statement:

if ($w > $width || $h > $height)

So, if $w is less than $width AND $h is less than $height, you'll jump straight down to:

imagedestroy($orig);

without actually doing anything to the file.I'd suggest adding an else statement at the end of your size check, which just does a straight file copy. Something like:

if ($w > $width || $h > $height){... all of your current resizing code ...}else{copy($orig, $dst);}imaegdestroy($orig);

This means that if the source image is already below the specified dimensions, it will be copied as-is to the appropriate location.

Link to post
Share on other sites

Cheers. Will have a go. This did not occur to me and now as you say it I feel that I should have known this... Will check this on Monday when I am back in office. Having thought I could work in my days off from home turned into a nightmare. The new internet connection is still not installed (you can never trust the dates they give you, can you?) and without a laptop a bit too bothersome... I think I sometimes rely too much on all my software stuff;-)Appreciate your help!Son

Link to post
Share on other sites

Ha, ha. I still have to come back. Although with the suggested change the files upload fine and with correct sizes into both folders (..banner/main and ...banner/thumb) I always get an error from line

	copy($orig, $dst);

as

copy(Resource id #7) [function.copy]: failed to open stream: No such file or directoryDate/Time: 6-29-2011 16:16:46Array(    [src] => ../banner/main/grey100By100.jpg    [dst] => ../banner/main/grey100By100.jpg    [width] => 210    [height] => 630    [chunks] => Array        (            [0] =>             [1] =>             [2] => /banner/main/grey100By100            [3] => jpg        )    [ext] => jpg    [orig] => Resource id #7    [w] => 100    [h] => 100)

This rather peculiar as it uploads just fine into relevant folders... Do you have any idea why this might be?Son

Link to post
Share on other sites

You error is saying copy is not working.

copy(Resource id #7) [function.copy]: failed to open stream: No such file or directory
And your $orig variable only works on image objects.
  $chunks = explode('.', $src);	$ext = $chunks[count($chunks) - 1];	if ($ext == 'jpg' OR $ext == 'JPG')	  $orig = imagecreatefromjpeg($src);	elseif ($ext == 'gif' OR $ext == 'GIF')	  $orig = imagecreatefromgif($src);	elseif ($ext == 'png' OR $ext == 'PNG')	  $orig = imagecreatefrompng($src);

copy requires 2 string parameters. The first parameter is the path to the file and the second is the destination path. So you'l wantcopy($src, $dst);

Edited by MrFish
Link to post
Share on other sites

Now I am with you. I change it tocopy($src, $dst);which works now and is great. Just to double-check:imagedestroy($orig);is fine without path, isn't it? I am getting paranoid now...Cheers,Son

Link to post
Share on other sites

imagedestroy() takes the image resource as parameter which is create by imagecreatefrom*() . not the path of the image

Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...