Quick & easy PHP image upload and resize script

I’ve been playing for a while to get a decent, well-working easy-to-use PHP image upload and resize script and haven’t managed to find one. I’ve been reading php.net extensively and I’m starting to understand the concept of the upload handling features of PHP itself and managed to finally get a script working (with the help of others!) which is small and easy to use.

First, this function must be placed near to the top of the page. This function is NOT my work, but from one of the comments on php.net, and works a treat.

function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)
	{list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
	$ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
		($TypeCode==3?"png":FALSE)));
	$CreateFunction="imagecreatefrom".$ImageType;
	$OutputFunction="image".$ImageType;
	if ($ImageType) {
		$Ratio=($ImageHeight/$ImageWidth);
		$ImageSource=$CreateFunction($Dir.$Image); 
		if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
			if ($ImageWidth > $MaxWidth) {
				$ResizedWidth=$MaxWidth;
				$ResizedHeight=$ResizedWidth*$Ratio;
			} else {
				$ResizedWidth=$ImageWidth;
				$ResizedHeight=$ImageHeight;
 	  		}
			if ($ResizedHeight > $MaxHeight) {
				$ResizedHeight=$MaxHeight;
				$ResizedWidth=$ResizedHeight/$Ratio;
			}
			$ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
			imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
			$ResizedHeight,$ImageWidth,$ImageHeight);
		} else {
			$ResizedWidth=$ImageWidth;
			$ResizedHeight=$ImageHeight;
			$ResizedImage=$ImageSource;
		}
		$OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
		return true;
	} else {
		return false;
	}
}

Secondly, this is the PHP script which will upload and resize the image from a form.

if ($_POST["uploadFile"]) {
	$dir = "directory/"; // directory of final image
	$finalimg = 'the-new-image.jpg'; // name of final image
	if (move_uploaded_file($_FILES['file']['tmp_name'], $dir.$finalimg)) { // upload it
		Resize($dir,$finalimg,$dir,$finalimg,180,130,80); // resize it
 	  	// and we're done
	} else{
		echo 'Problem!'; // oopps. Failed upon uploading
	} 
}

And finally, make sure that you add this code in your FORM attributes in your page.

 enctype="multipart/form-data"

Job done. Hopefully this’ll help someone out!

2 Comments

2 comments about Quick & easy PHP image upload and resize script

  1. Neil says:

    Dude can I use this – Might be of use on my site as I ditched my old gallery cause it was too long winded. Hope you’re good!!! x

  2. php answers says:

    Thanks for sharing, this is a very useful post :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>