Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Using PHP to create a cropped thumbnail on image upload

Posted on 2008-06-10
12
Medium Priority
?
693 Views
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 http://www.x-pose.org/blog/96/ .

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


Daniel

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.';
						break;
					case 2:
						print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
						break;
					case 3:
						print 'The file was only partially uploaded.';
						break;
					case 4:
						print 'No file was uploaded.';
						break;
					case 6:
						print 'No temporary folder was available.';
						break;
					default:
						print 'A system error occurred.';
						break;
				} // 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>';
 
exit();
 
// 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>';
 
}
 
   exit();
    
    }
    
// 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>';
 
exit();
 
// 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

0
Comment
Question by:dm404
  • 5
  • 2
  • 2
9 Comments
 
LVL 9

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.

see http://www.imagemagick.org/Usage/
0
 

Author Comment

by:dm404
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,

Daniel
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21769206
Here is an open source PHP thumbnail generator:  http://phpthumb.sourceforge.net/

These tutorials also look promising:  

http://icant.co.uk/articles/phpthumbnails/
http://php.about.com/od/advancedphp/ss/php_thumbnail.htm
0
Technology Partners: 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

by:dm404
ID: 21784676
Ok so I've got my heart set on using the tutorial http://www.partdigital.com/tutorials/gd-thumbnail

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');
      imagejpeg($thumb);
      imagedestroy($thumb);  

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

Thanks in advance,

Daniel
0
 
LVL 13

Accepted Solution

by:
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:
system($shell_cmd);

(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);
0
 

Author Comment

by:dm404
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 http://www.partdigital.com/tutorials/gd-thumbnail 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,

Daniel

<?
 
//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

0
 
LVL 13

Expert Comment

by:MasonWolf
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.
0
 

Author Comment

by:dm404
ID: 21849434
It's all working perfectly!

Thankyou very much!!
0
 

Author Closing Comment

by:dm404
ID: 31465938
Superb
0

Featured Post

Independent Software Vendors: 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!

Question has a verified solution.

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

Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

782 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