December 11, 2009

Automatic image resizing in PHP

Filed under: PHP, StructureCMS — joel.cass @ 9:54 am

One big issue in content management systems is that images are usually handled poorly. Even with the best file management capabilities, you can’t help users from uploading their 12 megapixel 15 megabyte images from their recent Christmas party and then chucking them into the content and resizing them down to fit the screen. The problem is that even though the image appears ’small’ in the browser, the full size image is downloaded and displayed, wasting bandwidth and slowing down the user experience.

A concept I really admired in Sitecore and have copied to StructureCMS is that resized images could automatically be created on the server-side and returned to the client simply by adding the parameters ‘w’ or ‘h’ to the URL, e.g. take these images for example:×120.gif

The attributes “w” and “h” can be added to the url to resize the image:×120.gif?w=60
test120x120, h=200

(if both parameters are defined, image is resized to ‘fit’ within the dimensions)

If you look at the images on their own, you will notice that they are resized by the server, and you can change the dimensions. The crunched down, resized version is sent back to the user, saving bandwidth and improving the user experience. Images are then cached so that future requests do not require any server resources.

How did I do this?

  1. I created image.php in the website root – this gets URL params and creates a new resized image (I’m not going to explain the code – it’s pretty simple)
  2. I installed the apache mod_rewrite module – this is as simple as opening your httpd.conf file and unhashing the line ‘LoadModule rewrite_module modules/’ (and then restarting apache)
  3. I created an .htaccess file that rewrites URL’s
  4. I then modified the tinyMCE image.js file to add the size attributes to the URL

The beauty of this modification is that it won’t break anything if apache nor mod_rewrite are installed. And, with some modification this code could be used on any website.


  1. I tried this but it says I need classes/includes/paths.php…

    Comment by Philip Peterson — July 4, 2010 @ 4:01 am

  2. Hi,

    This work was done as part of the StructureCMS project. In the project I have a file that calculates paths relative to the webroot, in order to get around the relative path limitations in PHP.

    You can download the paths.php file at, or better still, check out the entire project using SVN or download from That way, you will have all dependencies and will be able to extract out the functionality you need for your project.

    Comment by joel.cass — July 27, 2010 @ 11:44 am

RSS feed for comments on this post. TrackBack URL

Leave a comment