Image Resizing with php

One of the great things about php is its built in support for the gd image library which makes creating thumbnails from images quite trivial, although you still need to calculate the correct dimensions if you want your thumbs to be resized proportionally.

Here’s a function that takes a gd image, a maximum width and / or maximum height and returns a new thumbnail image that fits into these sizes. The function can either scale the image proportionally so the whole image fits completely into the new size, or scale and crop the original so that the thumbnail is exactly the maximum width and height.

Download from GitHub.

If either the maximum width or maximum height is 0 or null then the function calculates these proportionally which is useful if you want all thumbnails a certain width and height and don’t care about the other dimension.

You can also specify an rgb background colour which will force the thumbnail to be exactly $max_width x $max_height with any space at the left and right (or top and bottom depending on whether the source image is portrait or landscape) filled in with the background colour.

I’ve written a couple of scripts to show usage of this function below – one creates thumbnails for every image in the same directory as the script, then generates html to show these. The other extracts images from a zip archive through a standard form upload and creates and returns a zip archive containing generated thumbnails.

You can copy and paste the code, or download the zip file containing all three scripts.


Leave a Reply