This is a simple function that resizes and image using the GD add on for PHP.
Just a disclaimer: I know its not perfect, but i figured i would post it because the only other one on here is way confusing to some new PHP developers. Hopefully this one will help you learn how to use GD, and then you can write a better one.
Were going to be creating it in a function, so that we can re-use this wherever we need to. This particular function saves the thumbnail file to a directory on the server, you could actually skip saving the file and just print out the image itself if you would prefer to do that.
I tried to comment the code as best I could to help you understand. I’ll do a quick explanation right now though…
First we create the new image, I’m going to be saving them all as .jpg’s so im using the “imagecreatefromjpeg()” function. Then i check the existing directory to see if there is already a thumbnail made for the image, if there isn’t we’ll go ahead an make one. This particular system just takes the imagre size and divides it by the scale percentage that you pass in, you can also tell it to force to a particular size if you want to.
Once we create the thumbnail we save it and return the path to it. Now we can show that file to the user, and they didnt even know a resize happened, since its all server based, it doesnt stretch images out like the regular HTML image size tags.
// If they wish to scale the image.
// Create our image object from the image.
$fullImage = imagecreatefromjpeg($file);
// Get the image size, used in calculations later.
$fullSize = getimagesize($file);
// If there is NOT a thumbnail for this image, make one.
// Create our thumbnail size, so we can resize to this, and save it.
$tnImage = imagecreatetruecolor($fullSize/$scale, $fullSize/$scale);
// Resize the image.
// Create a new image thumbnail.
// Clean Up.
// Return our new image.
// If there is a thumbnail file, lets just load it.
// If they want to force whatever size they want.
elseif (isset($width) && isset($height))
As im just looking over the code, it doesnt look like the force size works, i will revise this when i get a chance.