Resize images on the fly without messing with image URLs

[EDIT: I’ve made this simpler with a follow up post: Mimicking’s image resize URIs]

Exporting a site for use on a standalone install is a joy to set up. The export and import system are simple to use and give little or no issues.

What is a problem is the automatic resizing of images that offers.

One can insert an image in the normal way and then append the image URI with some variables such as width (w) and height (h). This is also a d options, I assume this is for depth, but haven’t looked into it yet.

So an image URI might be

This URI would display the image resized to 300px wide and retain the aspect ratio.

Currently, do not offer this facility (that I have seen). So I’ve been working on how it might be done:

1st off, we need to set up a mod_rewrite rule to cater for image URIs that have query string variables. This can be added to a vhost config or the site’s .htaccess file. I prefer to use .htaccess

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} .(gif|png|jpg|jpeg)
RewriteCond %{QUERY_STRING} (w|h)=(.*)$
RewriteRule (.*) /my_resize_script.php?file=$1 [L]

Then we need a script (my_resize_script.php) to make use of the variables.

foreach ($queryString as $bit)
	$varBits = explode("=", $bit);
	$urlVars[$varBits[0]] = $varBits[1];

The output of this script as it is would be:

    [file] => wp-content/uploads/2010/03/high_res_horsey.png
    [w] => 300

As you can see, I’m not actually making use of the variables yet. But all of the information that it does extract can be given to a proper resize script, such as TimThumb.

This is all a bit messy right now. I would much rather be able to pass variables directly into a resize script rather than have to use an intermediary one. If anybody wants to give some pointers, please do 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.