Yup, there are a ton of these online if you go hunting (hotscripts.com and the like) however the server my site is running on does not have GD 2.0+ support so alot of them did not work. After figuring out what the hell GD was I was able to alter the code below to work for me, I am told it produces lower quality images but im not about to pay my hosting company the extra money they want to install the GD upgrade.
The code below will take a picture that you specify and resize it, its important to note that it overwrites the old picture (which is what most people want to do). If you need to store the resized image as a different file simply change the rename() command down at the bottom!
function resize_the_picture($picture_filename, $new_width, $quality) {
$your_directory_root = ""; e.g. "/home/httpd/vhosts/....." (this needs to be the server root you can't user [url]http://www[/url] or whatever
$original_picture = $your_directory_root . $picture_filename;
//create the full path on harddisk and check if file exists, otherwise die.
$fullPath = $original_picture;
if ( !file_exists ( $fullPath ))
die("File doesn't exist!");
//determine size and check if the file is really a picture, otherwise die.
$size = GetImageSize($fullPath);
if ( !$size )
die ("FILE ERROR!","File is not an image!");
//calculate the aspect ratio for resizing
$aspectRat = (float)($size[1] / $size[0]);
//calculate new x/y size, maintaining original aspect ratio
if($size[0] <= $new_width) {
return;
}
else {
$newY = $new_width * $aspectRat;
$newX = $new_width;
}
//create the destination image resource.
//always use true color here, or you'll get some real bad color shifts
$destImg = ImageCreate($newX, $newY );
//read the source image (original), use correct function depending on format
if ($size[2] == 2)
$sourceImg = ImageCreateFromJPEG ($fullPath);
else if ($size[2] == 3)
$sourceImg = ImageCreateFromPNG ($fullPath);
else
die("File is wrong type!!"); //can't read pic because of incompatible format (gif, bmp, etc.)
//here's the fun part.
//we need at least php 4.0.6 for clean resampling, otherwise use ugly resize =/
ImageCopyResized($destImg, $sourceImg, 0,0,0,0, $newX, $newY, $size[0], $size[1]);
//send the the created thumbnail to the browser
//save thumbnail to cache path.
//be careful with file rights, PHP must be able to write to the cache path.
$new_picture = $your_directory_root . "2" . $picture_filename;
imagejpeg($destImg, $new_picture, $quality);
$deletedfile = @unlink($original_picture);
rename($new_picture, $your_directory_root . $picture_filename);
}