How can I upload an automatically resize an image on my website?

I often need to upload images to my website, but I’d like them to be automatically resized when they’re uploaded. How can I do this??


I got this question from from a colleague of mine who was answering some questions for a client. His client’s requirements were a bit more complex than just this question, but I thought this would be a good one to put up on AskOwen and use it as a tutorial for some interesting PHP techniques. Here’s some PHP code that will accomplish the request:


<?php
// Image uploaded and resizer
// from http://AskOwen.info
?>
<html>
<head>
<title>Image Uploader and Resizer</title>
</head>
<body>
<?php
if (array_key_exists('btn', $_POST)) {
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);
imagedestroy($src);
imagedestroy($tmp);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile"/>
<input id="btn" name="btn" type="submit"/>
</body>

Here’s a quick run through the algorithm:

  1. Pick up the file that has been uploaded by the form
  2. Get the images width and height
  3. Calculate the correct height to maintain the aspect ratio of the image
  4. Create a memory space for the new image
  5. Use imagecopyresampled, a PHP function that resizes the image for you, to generate the new image
  6. Write the file to disk
  7. Clean up memory space

It’s quite straight forward once you know that PHP has the graphical functions you need to accomplish this.  It’s worth nothing that there’s another PHP function that can resize an image for you also, called imagecopyresized, however this function only uses 255 colours to generate the target image and so doesn’t maintain the fidelity of the image so well. This may be fine if you have some line art you’re converting, but if you wanted to resize that beautiful photo you took last time you went on holiday and stayed at one of the Hilton Head rentals you hear so much about, well, you really want as clear an image as possible.

As I said above, this is just the bare bones of an image resizing script, but it illustrates some of the graphical functions that PHP has available (through the GD library) that can help you produce some really useful scripts.

Leave a Reply

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