PHP Upload and Resize an Image

11/22/2013 9:13:15 PM

The follow php page will allow you to upload a file an image and then resize the image if it is greater than a certain width threshold.

This code does not do error checking to ensure the file is an image.

This code requires SimpleImage (http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/) to do the actual resizing.

<?php

include_once("SimpleImage.php");

if($_SERVER["REQUEST_METHOD"] == "POST")
 {
     $image = $_FILES["file"]["name"];
     $mimeType = $_FILES["file"]["type"];
     $size = ($_FILES["file"]["size"] / 1024);
     $tmpName = $_FILES['file']['tmp_name'];

    if ($image && $size > 0)
    {
        $maxImageWidth = 1024;

        $filename = stripslashes($_FILES['file']['name']);           
		$imgDir = "C:\\Uploads\\images\\";

		//resize and save image
		$image = new \Common\SimpleImage();
		$image->load($tmpName);
		if ($image->getWidth() > $maxImageWidth)
		{
			$image->resizeToWidth($maxImageWidth);
		}
		else
		{
			//$image->resizeToWidth($image->getWidth());
		}
		$image->save($imgDir . $newFilename);                   
    }
 }

?>

<form action="/upload/" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" value="Upload" />
</form>