7 days of php add-ons - Day 4: image resizer

Saturday, 11 April 2009


Hi, for day four of 7 days of php add-ons I will be loooking at an excellent image resizing script.

Having an easy to use image resizing script is a fantastic tool to have especially when you have a site that uses a CMS, if you have a catalogue of items or if you have an inventory system.

The idea is that you allow your users or administrators to upload an image of any dimension or size (although you would want to put restrictions on the file size) and the you can pass the location of the file through this script and it will allow you to resize the image to a certain size and maintain the aspect ratio of the image.

This script also allows you to crop your image to a certain size square while maintaing the aspect ratio.

In basic terms maintaing the aspect ratio means resizing your image but not having it strecth or blur because of the new dimension. So if it needs to be shrunk or made larger it will still maintain the width to height ratio of the original image.

The image resizing script I've chosen is from Joe Lencioni over at Shifting Pixel. You can download the script and read his post about it here.

After downloading it's easy as pie to set up. All you need to do is create an imagecache folder in the same directory as the resizer script and give it the correct permissions.

Then to resize an image it's as easy as calling the script in the img src. Like this:

<img src="/image.php/coffee-bean.jpg?width=200&amp;height=200&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" />


And to resize and crop, you pass in the cropratio variable:

<img src="/image.php/coffee-bean.jpg?width=150&amp;height=150&amp;cropratio=1:1&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" />


The first part of the src attribute is the location of the php script followed by the name. The part image= is the absolute path to the image.

Here are the other paramters that can be passed in:

// Parameters need to be passed in through the URL's query string:
// image absolute path of local image starting with "/" (e.g. /images/toast.jpg)
// width maximum width of final image in pixels (e.g. 700)
// height maximum height of final image in pixels (e.g. 700)
// color (optional) background hex color for filling transparent PNGs (e.g. 900 or 16a942)
// cropratio (optional) ratio of width to height to crop final image (e.g. 1:1 or 3:2)
// nocache (optional) does not read image from the cache
// quality (optional, 0-100, default: 90) quality of output image


This script is released under the Creative Commons Attribution-Share Alike 3.0 United States license. Please refer to the license section of the blog entry for further details about giving credit to the author.
blog comments powered by Disqus