Resize images on the fly without messing with image URLs
By Iain Cuthbertson
[EDIT: I’ve made this simpler with a follow up post: Mimicking wordpress.com’s image resize URIs]
Exporting a wordpress.com site for use on a standalone wordpress.org 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 wordpress.com 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 http://myrant.net/wp-content/uploads/2010/03/high_res_horsey.png?w=300
This URI would display the image resized to 300px wide and retain the aspect ratio.
Currently, wordpress.org 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.
<?php
$urlBits = explode("?", $_SERVER['REQUEST_URI']);
$queryString = explode("&", $urlBits[1]);
$urlVars = array('file' => $_GET['file']);
foreach ($queryString as $bit)
{
$varBits = explode("=", $bit);
$urlVars[$varBits[0]] = $varBits[1];
}
print_r($urlVars);
The output of this script as it is would be:
Array
(
[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 🙂