Resize/Thumbnail Images With PHP

danielneridanielneri WP V.I.P.VPS - Virtual Prince of the Server
Introduction:

Image resizing is relatively very simple if you know how to work with images in PHP. Make sure you have the GD library installed before attempting this tutorial.

[PHP]
<?php

if(isset($_POST))

{

//make sure this directory is writable!

$path_thumbs = "/path/to/thumbs/";

//the new width of the resized image, in pixels.

$img_thumb_width = 100; //

$extlimit = "yes"; //Limit allowed extensions? (no for all extensions allowed)

//List of allowed extensions if extlimit = yes

$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");

//the image -> variables

$file_type = $_FILES;

$file_name = $_FILES;

$file_size = $_FILES;

$file_tmp = $_FILES;

//check if you have selected a file.

if(!is_uploaded_file($file_tmp)){

echo "Error: Please select a file to upload!. <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";

exit(); //exit the script and don't process the rest of it!

}

//check the file's extension

$ext = strrchr($file_name,'.');

$ext = strtolower($ext);

//uh-oh! the file extension is not allowed!

if (($extlimit == "yes") && (!in_array($ext,$limitedext))) {

echo "Wrong file extension. <br>--<a href=\"$_SERVER[PHP_SELF]\">back</a>";

exit();

}

//so, whats the file's extension?

$getExt = explode ('.', $file_name);

$file_ext = $getExt[count($getExt)-1];

//create a random file name

$rand_name = md5(time());

$rand_name= rand(0,999999999);

//the new width variable

$ThumbWidth = $img_thumb_width;



/////////////////////////////////

// CREATE THE THUMBNAIL //

////////////////////////////////



//keep image type

if($file_size){

if($file_type == "image/pjpeg" || $file_type == "image/jpeg"){

$new_img = imagecreatefromjpeg($file_tmp);

}elseif($file_type == "image/x-png" || $file_type == "image/png"){

$new_img = imagecreatefrompng($file_tmp);

}elseif($file_type == "image/gif"){

$new_img = imagecreatefromgif($file_tmp);

}

//list the width and height and keep the height ratio.

list($width, $height) = getimagesize($file_tmp);

//calculate the image ratio

$imgratio=$width/$height;

if ($imgratio>1){

$newwidth = $ThumbWidth;

$newheight = $ThumbWidth/$imgratio;

}else{

$newheight = $ThumbWidth;

$newwidth = $ThumbWidth*$imgratio;

}

//function for resize image.

if (function_exists(imagecreatetruecolor)){
64.
$resized_img = imagecreatetruecolor($newwidth,$newheight);

}else{

die("Error: Please make sure you have GD library ver 2+");

}

//the resizing is going on here!

imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

//finally, save the image

ImageJpeg ($resized_img,"$path_thumbs/$rand_name.$file_ext");

ImageDestroy ($resized_img);

ImageDestroy ($new_img);


}


//ok copy the finished file to the thumbnail directory

move_uploaded_file ($file_tmp, "$path_big/$rand_name.$file_ext");

/*

Don't want to copy it to a separate directory?

Want to just display the image to the user?

Follow the following steps:


2. Uncomment this code:

/*

/* UNCOMMENT THIS IF YOU WANT */

//echo "IMG:<img src=\"$path_big/$rand_name.$file_ext\" />";

//exit();

//*/



//and you should be set!



//success message, redirect to main page.

$msg = urlencode("$title was uploaded! <a href=\"Resize.php\">Upload More?</a>");

header("Location: Resize.php?msg=$msg");

exit();

}else{

//if there is a message, display it

if(isset($_GET))

{

//but decode it first!

echo "<p>".urldecode($_GET)."</p>";

}

//the upload form

echo "

<form action=\"$_SERVER[PHP_SELF]\" method=\"post\"enctype=\"multipart/form-data\">\n

<p>File:<input type=\"file\" name=\"vImage\" /></p>\n

<p><input type=\"submit\" name=\"submit\" value=\"Submit\" /></p>";

}

?>
[/PHP]

Explanation:

We start off with an if statement to check whether or not the form has been submitted. Majority of the code has been commented to the best of my ability at this time, but I will do my best to explain it. First of all this code has been thoroughly tested in Linux and Windows environments. As long as you have GD v2.0+ you should be set!

If the form has not been submitted, we start processing the image. The first few things you would want to do is set the variables like the thumbnail path (if you want to store the image on the server ), and the width maximum width of the resized image, in pixels.

Then there is an array of allowed extensions. If you choose to enable limitation of file types allowed to be uploaded, you should worry about this, otherwise just ignore it, although don't forget to change $extlimit to "no".

We now check if image has been submitted via HTTP POST and not some malicious user trying to hijack your server, or simply, that the user selected a file to upload. If the test returns false, an error message is displayed, and the script is killed immediately. If the test returns true, the file is uploaded to a temporary folder on your server.

Next we check the files extension. If you choose to limit the file types allowed to be uploaded, this section makes sure that the selected file has a valid extension, otherwise it just gets ignored.

We then create a random file name (so we never have two files with the same name...ever!), and define the new image width.

Here comes the important part. The thumbnail creation.

Now that we have the file uploaded into the temporary folder, we can use the GD library to modify it and either save it to disk or display it to the user.

We check the image types to ensure we use the right function. Then move on to calculate the various measurements required to resize the image. Some math here, some more math there, and tada! We come up our result. We now use the imagecreatetruecolor() function to create the new, resized image.

Now here comes the end! We move it to the specified path, and then redirect the user to the index with a message saying that the upload was successful.

That'll be all for now. Lots more to come so don't go anywhere!

Tips:

* Be careful when setting the image width and storage paths!
* There is lots of room for customization in this script. Feel free to tweak it to your needs. If you do actually end up using it for personal purposes, some credit or a link back wouldn't hurt :D

Zip Download: resize.zip (1.74 kb)
ban1.gif
Sign In or Register to comment.