Use And Tweak timthumb Script For WordPress Blog

Update: I don’t use the Timthumb script anymore because it has a security vulnerability. Please use it at your own risk.

TimThumb is a small open source library aimed at providing resized copies of given images. TimThumb was developed by Ben Gillbanks, who first created this script for the WordPress theme Mimbo Pro. It handles cropping, zooming, and resizing web images in several formats such as jpg, png, and gif. It’s very useful and simple enough.

Follow the guide below to integrate Timthumb into your WordPress blog:

1. Grab the timthumb.php script from Google Code.

2. Put it under your themes folder. For example, my themes folder is “codemaniac” — I put it in wp-content/themes/codemaniac/tools/timthumb.php.

3. To use timthumb.php you have to use a custom field in every post. I’m using the name “thumb”. Read more about WordPress custom fields here.

4. Now use the code below to use Timthumb:

<?php if( get_post_meta($post->ID, "thumb", true) ): ?>
<img class="thumb" width="50" height="50" src="<?php bloginfo('template_directory'); ?>/tools/timthumb.php?src=<?php echo get_post_meta($post->ID, "thumb", $single = true); ?>&amp;h=50&amp;w=50&amp;zc=1" alt="<?php the_title(); ?>" />
<?php endif; ?>

Explanation: The code above checks whether the post meta named “thumb” exists for the current post. If it exists, it shows the output image from Timthumb. timthumb.php?src=/path/to/image.png&width=50&height=50&zc=1 will output image.png at 50×50 pixels in size.

Timthumb has a very good cache mechanism, which is why it’s a handy and less resource-consuming script. Even though it’s already a good and handy script, there are still ways to tweak it for more efficiency and speed.

Tweak Timthumb script:

1. Image quality. This controls PNG image compression with PHP’s imagepng function. The default compression is 5. You can increase it to 9. Change this code:

$quality = preg_replace("/[^0-9]+/", '', get_request('q', 50));

to

$quality = preg_replace("/[^0-9]+/", '', get_request('q', 100));

2. Increase “CACHE_SIZE” — the default is 250. Increase it to 1000. Most hosting servers give unlimited or very large space. Increasing it to 1000 files in the cache folder will increase performance a little bit, as there is more cache space.

3. Increase the Expires header. Find this code:

$gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';

Change to:

$gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +30 days')) . ' GMT';

This increases the Expires header to 1 month, so the image file will be cached in the user’s browser for 1 month.