Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Using PHP to create a cropped thumbnail on image upload

Posted on 2008-06-10
Medium Priority
Last Modified: 2010-04-21
Hi there,

I'm looking for some help doing the following:

I want to create a cropped thumbnail that looks perfectly scaled in a square say 100px by 100px. Something like found on .

I want to create it upon file upload.

I want to store it in a folder called .../uploads/thumbnails.

Finally I want to add thumb to the name of the thumbnailed image.

So I'v done some research and found scripts but wasn't sure how to apply it for my requirements i.e how to create cropped thumbnails, how to save it to file?

I've included my PHP process for when an image is uploaded. As I'm probably going to need help inputting it correctly.

I appreciate this could be a long winded question so any help at this stage is very much appreciated.

Thanks in advance


else {
$allowed = array ('image/gif', 'image/jpeg', 'image/jpp', 'image/pjpeg', 'image/bmp');
if (in_array($_FILES['eventflyer']['type'], $allowed)) {
// Move the file over
if (move_uploaded_file($_FILES['eventflyer']['tmp_name'], "uploads/{$_FILES['eventflyer']['name']}")){
} else { // Couldn't move the file over
echo '<p><font color="red" size="+1">File could not be moved over because: <b>';
//Print a message based on the error.
switch ($_FILES['eventflyer']['error']) {
          case 1:
						print 'The file exceeds the upload_max_filesize setting in php.ini.';
					case 2:
						print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
					case 3:
						print 'The file was only partially uploaded.';
					case 4:
						print 'No file was uploaded.';
					case 6:
						print 'No temporary folder was available.';
						print 'A system error occurred.';
				} // End of switch.
				print '</b></font>.</p>';
  } // End of move....IF
} else { //Invalid image type
    echo '<p><font color="red" size="+1">Please upload an image file such as jpeg, jpg, gif<b></font>';
    unlink ($_FILES['eventflyer']['tmp_name']); // Delete file.
$query7 = "INSERT INTO event (EventName, EventDate, EventTime, EventPrice, EventDescription, VenueID) VALUES ('$enm', '$edt', '$etm', '$epr', '$ede', '$vid')";
$result7 = mysql_query($query7);
  if (mysql_affected_rows() ==1) { // If it ran ok.
// Print a message
echo '<h3>Your event been added however we could not add the flyer!  Click<a href="venue.php">here to return</a> </h3>';
// Print a message
} else { // Didn't run ok
echo '<h3>Your event been added however we could not add the flyer!  Click<a href="venue.php">here to return</a> </h3>';
// Validate the type; Should be image & Set variable
$efl =($_FILES['eventflyer']['name']); 
if ($enm && $edt && $etm && $epr && $ede && $vid && $efl) {
$query9 = "INSERT INTO event (EventName, EventDate, EventTime, EventPrice, EventDescription, VenueID, EventFlyer) VALUES ('$enm', '$edt', '$etm', '$epr', '$ede', '$vid', '$efl')";
$result9 = mysql_query($query9);
if (mysql_affected_rows() ==1) { // If it ran ok.
echo '<h3>Your event has been added. Click<a href="venue.php">here to return</a> </h3>';
// Print a message
} else { // Didn't run ok
echo '<h3>Your event has NOT been added. We apologize!  Click<a href="venue.php">here to return</a> </h3>';
} // End of image proccess

Open in new window

Question by:dm404
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
  • 2

Expert Comment

by:Rob Siklos
ID: 21755231
I did something like this a while ago, but I'm fuzzy on the details.

I think I used the command-line tool ImageMagick, which has a whole bunch of command line options that definitely can address your requirements.


Author Comment

ID: 21764049
Hi Rob263,

I think I'd be more comfortable using GD instead of imagemagick as I don't really understand how to use imagemagick.

Any good GD tutorials online that does the above?

Thanks in advance,


Expert Comment

by:Rob Siklos
ID: 21769206
Here is an open source PHP thumbnail generator:

These tutorials also look promising:
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 21784676
Ok so I've got my heart set on using the tutorial

I think my GD library is playing up as when I try and run the script above it always just hangs and does nothing!

Whilst that is a work in progress there are a few changes that need to be made to meet my aims.

1) When to start the above script? I'm guessing after the file has been moved over and name has been set in the DB through the query. I.e line 88 of my script up above.

2) The first part of the script is to set the src. I was hoping to do this by using the $efl variable in a directory such as http://localhost/mywebsite/uploads/$efl. Is this correct?

3)Finally the tutorials outputs the file by using

      //final output  
      header('Content-type: image/jpeg');

How could I change so that the thumb isn't displayed but saved to uploads/thumbs/ ??

Thanks in advance,

LVL 13

Accepted Solution

MasonWolf earned 2000 total points
ID: 21840619
Ok, first off, I want to agree with the first expert, rob, that this would be a job more easily suited to IM over GD. To use IM, you simply create your shell command as a string, and then pass it to:

(That's the recommended method, backticks also work but are a little harder to interpret later)

However, since you're set on GD, there's a couple things you should know. First of all, GD uses a LOT of memory to do its image manipulation operations, so depending on your memory execution limits, you will quite possibly have the script hang using GD where it wouldn't have with IM. Second, the thumbnails IM creates are, thanks to the more advanced re-sampling algorithms, generally of a nicer quality than what GD will get you. It's like the difference between resizing something in Adobe Photoshop versus MS Paint. Sure, they can both technically do it, but Photoshop gives you a much nicer result.

So, that aside, you asked 3 questions in your last post.

I haven't looked at the specific script you're using, but in general you can start your image manipulation as soon as the form has posted, by simply using the $_FILES[file]['tmp_name'] as your source location. However, waiting until after you've moved the file is fine too.

Next, it is possible to set the source using the public html path, but only if you have php set to allow_url_fopen = on. Otherwise you need to provide the location relative to the calling script's path or pass the absolute path on the server.

Last, you can pass a filename parameter to imagejpeg if you want to save the result to a file rather than output it. Syntax is:
imagejpeg($im, $filename);

Author Comment

ID: 21842553
Hi Masonwolf,

Thanks for your comments!!

The good news is that I've played around and got GD not hanging.

Before I do it upon upload I want to do it with a saved image.

I can get the script from to output a thumbnail using the header :).

The bad news is that I'm having trouble using the imagejpeg() function. The error always reads Warning: imagejpeg() [function.imagejpeg]: Unable to open '/uploads/Garden.jpeg' for writing: No such file or directory in...

This is weird as all my images are currently stored there?!? Any ideas why it won't save?

Thanks again,


//Your Image
$imgSrc = "Garden.jpg"; 
//getting the image dimensions
list($width, $height) = getimagesize($imgSrc); 
//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc); 
//setting the crop size
if($width > $height) $biggestSide = $width; 
else $biggestSide = $height; 
//The crop size will be half that of the largest side 
$cropPercent = .5; 
$cropWidth   = $biggestSide*$cropPercent; 
$cropHeight  = $biggestSide*$cropPercent; 
//getting the top left coordinate
$c1 = array("x"=>($width-$cropWidth)/2, "y"=>($height-$cropHeight)/2);
// Creating the thumbnail
$thumbSize = 60; 
$thumb = imagecreatetruecolor($thumbSize, $thumbSize); 
imagecopyresampled($thumb, $myImage, 0, 0, $c1['x'], $c1['y'], $thumbSize, $thumbSize, $cropWidth, $cropHeight);
// Save the image to uploads/thumbs
$filename = "/uploads/Garden.jpeg";
imagejpeg($thumb, $filename);

Open in new window

LVL 13

Expert Comment

ID: 21842773
"/uploads/Garden.jpeg" is an absolute path. I'm guessing you want to use a path name relative to the current working directory (cwd).

Try "uploads/Garden.jpeg" and see if that works.

Author Comment

ID: 21849434
It's all working perfectly!

Thankyou very much!!

Author Closing Comment

ID: 31465938

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question