Your friendly neighbourhood geek

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:

Calculate the correct height to maintain the aspect ratio of the image

Create a memory space for the new image

Use imagecopyresampled, a PHP function that resizes the image for you, to generate the new image

Write the file to disk

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.