Crop and adjust the quality of images on the fly by using TimThumb

I stumbled across TimThumb while working with the Smooth Slider WordPress plugin. For some odd reason, Smooth Slider was converting all my nicely optimized JPGs into huge PNGs (60kb .jpg turned into a 400kb png). This was unnecessarily slowing down the load time for the website I was working on, so, I decided to investigate.

It turned out the culprit was an older version of the TimThumb.php script. After downloading the latest version from Darren Hoyt’s site and uploading it to the appropriate directory in Smooth Slider, everything worked great. In fact, I was really impressed about how easy TimThumb made it to scale and crop my images.

How to use TimThumb

Grab a copy of the source code and save it into a new document called ‘timthumb.php’. Then place that file in the scripts folder on your site (ex: /scripts/) and call the image like this:

<img src="/scripts/timthumb.php?src=/images/pic.jpg&h=75&w=75&zc=1&q=100">

The query string determines what image is going to be cropped, and the properties of the new image:

?src=/images/pic.jpg&h=75&w=75&zc=1&q=100

Here is the breakdown of the different parameters:

  • w: width
  • h: height
  • zc: zoom crop (0 or 1)
  • q: quality (default is 75 and max is 100)
TimThumb Example

Image on the left is the original and the one on the right is it's TimThumb counterpart. Notice how the script both scales and crops relative to the center of the image.

Some important things to note:

  • TimThumb requires the GD library, which is available on any host sever with PHP 4.3+ installed.
  • Once installed and in-use, TimThumb will automatically create a /cache/ subfolder with proper write-permissions. If your host server doesn’t allow this by default, be sure to manually change the /cache/ folder permissions to 777.
  • In addition, make sure the folder which contains TimThumb is set to 777.
  • As in the example, use absolute paths for your script and images
  • To really speed things up and make use of the advanced caching checks added to the script, copy these rules to your .htaccess file.

Conclusion

TimThumb looks like a great script for resizing images on WordPress templates and plugins. Including a cropping script gives the developer control over what is displayed on the site, regardless of what size image is uploaded. This both improves the user’s experience as well as ensures a consistent style for the template/plugin. I plan on using TimThumb in the future and encourage you to try it for yourself. Also, be sure to check out Darren Hoyt’s site for the latest code updates and demo.