On the Fly PHP Image Resizer


I recently learned about srcset on episode 99 of The Web Ahead. Knowing a responsive site overhaul was on the horizon I set out to find a PHP script to resize images on-the-fly since I anticipate needing five different sizes for each image. After looking at a few and not particularly liking any of them I decided I would write my own.


  1. The resizer should support png and jpeg.
  2. There should be no need to specify both width and height. I’m almost always worried about width anyway. Why would I want to go around specifying the height of every graphic or image I resize?
  3. Resized images should be stored in a cache and served without any involvement from PHP.
  4. Resizing to a square. There are so many occasions when having square images helps with layout but I didn’t want to ask our designers to spit out square versions of all our images.


First, I had to learn to resize images using ImageMagick. This wasn’t difficult given what I needed to do. Next, I had to come up with a caching scheme so the resizer wouldn’t be called more than once for a given request. I decided to organize the images as they are presently stored but under a new sub-folder called /cache along with the resize command. After an image is cached Apache can check for it’s existence by prepending /cache to the request URI.

TO make this a real devleopment section you should discuss delivering the file with PHP and avoiding the immediate HTTP requests by seetting expires headers and returning error codse in the HTTP Headers. Much work to do here.


A call to /graphics/100sqp/jpegExample.jpg will be checked against the cache and if it’s not found will be redirected to the resizing script. Resize.php will use the request URI to find the image and resize it to the requested size using the specified method and store it in /cache/graphics/100sqp/jpegExample.jpg which matches the request URI exactly with the exception of the /cache subdirectory. Any subsequent call to /graphics/100sqp/jpegExample.jpg will be served by Apache bypassing the resize script.


Resize commands are expressed as a number of pixels followed by a resize method.


w orĀ h

Resizes proportionately to the specified width or height.


Resizes to a square by padding out the shorter side of the original image.


Resize to a square by trimming the long side of the original image.











Project can be found at github.com/michaelgroh/php-image-resizer.