its_me its_me - 7 days ago 5
PHP Question

How does WordPress.com resize images dynamically?

NOTE: This question is tricky (to decide whether it pertains to SO or not), but this is no simple WordPress question.

I've heard that WordPress.com has a separate layer of infrastructure (Nginx based servers) for images that is pretty much independent of the hosted WordPress blogs.

The thing is, any image on a WordPress.com blog can be resized simply by appending

w
(width) and/or
h
(height) parameters like so:

http://serenescribe.files.wordpress.com/2012/04/cropped-p1000206.jpg?w=400


http://serenescribe.files.wordpress.com/2012/04/cropped-p1000206.jpg?h=200


Is the script available on the web? (Because, they always say "We’re strong believers in Open Source, and we try to open source everything we can.")

Most of the dynamic image resizing scripts out there are insecure and very vulnerable to attacks (Tim Thumb), or badly written, or come at the cost of performance. Is/Are there any good ones?

PS: There are probably several other dynamic image resizing scripts, like TimThumb, for example. But I am only interested in what WordPress.com blogs use.

Answer

(1) Use TimThumb, then re-sizing your images is as simple as appending some parameters:

http://example.com/timtumb.php?src=wp-content/uploads/2010/03/high_res_horsey.png&w=300&h=100

(2) Then add these rewrite rules in your site's root .htaccess file:

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_URI} \.(gif|png|jpg|jpeg)
RewriteCond %{QUERY_STRING} (w|h)=(.*)$
RewriteRule (.*) /full/path/to/timthumb.php?src=$1&%1=%2&%3=%4 [L]

Quick breakdown of the rules:

  1. Check that the URI exists as a file.
  2. Check that the URI in question is an image. Expand to other formats as needed.
  3. Check that one or both of width and height are being altered.
  4. Pass the file following to timthumb as variables:
    • $1 = filename
    • %1 = w or h
    • %2 = value of w or h
    • %3 = w or h
    • %4 = value of w or h

(3) Now, you can pretty much resize your images as you would on WordPress.com, i.e. like so:

http://example.com/wp-content/uploads/2010/03/high_res_horsey.png?w=300&h=100

From http://www.myrant.net/2011/03/07/mimicking-wordpress-coms-image-resize-uris/