Using Timthumb with Imagemagick

/ PHP / by Paul Robinson / 71 Comments
This post was published back on December 27, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Updated: 11/04/2011

After a lot of requests, I’ve updated the post to work with the new version of timthumb. It is fairly similar, but different enough for it to have caused problems. The only problem is that because this is a quick dirty hack (I believe the developer of timthumb should add full support for ImageMagick if he wishes) it disables all the filters & the ability to choose the crop location (center, left, etc).

Original Post – Updated For Version 1.26

Ok so recently I’ve been doing a lot of WordPress theme work & one of the popular ways to generate thumbnail sizes that are different from WordPress’, especially cropped ones, is to use the thumbnail generating script Timthumb. It’s a great script that generates thumbnails at the size you request, it also allows cropping & cache generation to stop the strain on the server. However on a shared or low memory server it can cause problems due to it’s use of GD. GD can be a huge memory hog, Imagemagick however can be told to use a specific amount of memory before dumping to swap or HDD. Great if you are on a shared server or a server with limited memory.

Anyway I altered Timthumb to use Imagemagick as there is no option built in to it. So I thought I’d share it for everyone who wants to use it. I can only share the code I used though & not the script just in case. Don’t want to run into any license problems. 😉

First we define a new constant, just to make it easy to alter our path the Imagemagick’s convert.

Now that we have an easy way to call our convert path we can continue. First though a quick note. Timthumb has support for filters, due to Imagemagick having different parameters I have not added support for them. Ok, now that’s out of the way we can get back to the code. I would comment out the bits of code no longer needed. It will not increase the size of the file as we aren’t actually adding that many lines of code to it.

Now is a tricky bit to explain. You need to find this line of code:

and comment out everything after it (using /* */) until you reach this line:

Then you need to change that line of code to this:

Then comment out this line:

Now find this function:

and change it to this:

That should be it. It seems to work fine on my server. I am not adding a demo as the amount of hits I may get on it might cause a problem even for imageMagick. However it really does work. If you have any problems please let me know. I’ll try and give support but as I’m not actually the developer who wrote timthumb my knowledge of it is limited. I’ll try and add in support for changing the crop location at some point, but for the minute I hope this helps those looking for ImageMagick support in the latest (as of now 1.26) version of timthumb.

71 Comments

Author’s gravatar

Hi Interesting, I use the same theme as you and have massive issues with TimThumb, your solution looks a little tricky for me to follow though.

I would like to know what plugin you are using for on this site for the four ad boxes at the top if possible mate 🙂

Reply
Author’s gravatar

Not a problem. The plugin is called Adrotate & is available from the WordPress plugin directory. It requires a little setup but not too much & most of it is done via the admin.

Hope that helps. 😉

Author’s gravatar author

Forgot to mention that this patch will only be usefull if you have Imagemagick installed. If you don’t then unfortunately there isn’t a lot you can do. One thing I did find is that if you use timthumb on a large site with a lot of images Timthumbs pre-set cache amount may be too small. If you open the timthumb cache folder in a SFTP client and see if there a 250 files. If so your problem may be that you have more thumbs for timthumb to create than it can cache. This happened on a image heavy client site I worked on recently.

If that is the problem the just open up the timthumbs file and increase the cache number near the top of the file. Hope that helps a little more. 😉

Author’s gravatar

It was a great moment that I have landed here in your post. I’m really learning a lot. Thanks. Keep it up. You’re helping lot of people.

Reply
Author’s gravatar

Hi Paul,

If you don’t mind can I know where I can get Imagemagick? So that i can also use this.

Reply
Author’s gravatar author

Imagemagick is a unix/windows program used by servers to manipulate images, if can be installed quite a few different ways, depending upon your platform.

On Windows you just search on google for imagemagick & download the windows binary. If you are on Ubuntu or a Unix platform with access to apt or a software repository there is normally a version available on there. Finally you can compile it manually using the instructions on Imagemagick’s website. 😉

Author’s gravatar

I haven’t heard about this before. I want to thank you for the codes you have preferred and shared to us. It will really help a lot to me and to everyone that will see this.

Reply
Author’s gravatar

Very nice article, Thanks for posting this. Awesome work. I’ll be back again.

Reply
Author’s gravatar

Bro, do you have a new version? I tried this, and it gives me errors on the new timthumb script

Reply
Author’s gravatar author

Sorry I haven’t. Can you tell me what the errors are as I’ve just had a scan through the new version of timthumb and it doesn’t look that much different.

If you can give me those, I’ll see if I can update the post to correct the problems. 😉

Author’s gravatar

Or can you please upload your version of this somewhere? im not getting notifications when you reply, so can you send it to xcingix@gmail.com

Author’s gravatar author

Hi Danny,

I only have the old version modified to work with imagemagick, but then it also has the htaccess modification in it too so I’m not sure it would be much help.

There is one of two things you could do. Either try modifying an older version of Timthumb, or if you are able to wait a couple of days I’ll see if I can make the new version work with Imagemagick.

I’ve just been extremely busy recently and haven’t had much time to work on tutorials, sorry if this isn’t the best news. I think Timthumb has changed too much now to apply this tutorial to it so I’d have to take a look and modify it to work.

Although just looking you could try one small thing. It seems Timthumb now checks the mime type for a jpeg. You could place another copy of the imagemagick code (line 221-224) after line 218 and also comment out line 218. All the line numbers refer to the numbers in your pastebin code.

I hope that helps. Let me know what happens & failing that I’ll try to update the code for the new version in the next couple of days.

Author’s gravatar author

Just noticed, I can’t find your definition for the constant MAGIC_PATH. Have you added it to the top of the file?

Author’s gravatar

Actually, I found it missing a ‘}’ on line 203 in that version. the error went away, but the script is still not working

Author’s gravatar

When I try to look at one of the images, im getting
[code]image /home/danny/public_html/wp-content/uploads/2011/03/betty-rose-super-hero-e1300000056131-260×364.jpg not found
Query String : src=http://nybodyart.com/wp-content/uploads/2011/03/betty-rose-super-hero-e1300000056131-260×364.jpg&q=100&a=t&h=142&w=222
TimThumb version : 1.19[/code] for
[code]http://nybodyart.com/wp-content/themes/nyb/scripts/timthumb.php?src=http://nybodyart.com/wp-content/uploads/2011/03/betty-rose-super-hero-e1300000056131-260×364.jpg&q=100&a=t&h=142&w=222[/code]

Author’s gravatar author

Okay. Well it seems that Timthumb has stopped using GD to produce the images or you wouldn’t have that error, so in a small way that’s good news.

Some stupid questions that I have to ask though. First do you have Imagemagick installed on your server & what version is it? Also is the path to Imagemagick correct?

Author’s gravatar author

Sorry had to get some sleep.

The error you are getting seems to be generated by the get_document_root() function. Which is strange since there is not modification needed to make that function work with imagemagick.

Is the full path it is generating to the image correct? I know the part from wp-content is as I checked & I get taken to the image, but is everything before that correct? Timthumb seems pretty convinced it isn’t.

Author’s gravatar

I’m pretty sure of it
http://nybodyart.com/wp-content/themes/nyb/scripts/timthumb.php?src=http://nybodyart.com/wp-content/uploads/2011/03/betty-rose-super-hero-e1300000056131-260×364.jpg&q=100&a=t&h=142&w=222 [code]<img src="<?php bloginfo(‘template_url’); ?>/scripts/timthumb.php?src=<?php echo catch_that_image(); ?>&amp;q=100&amp;a=t&amp;h=142&amp;w=222" alt="<?php echo (get_post_meta($post->ID, "post-img-alt", true)) ? htmlspecialchars(get_post_meta($post->ID, "post-img-alt", true)) : the_title(); ?>" width="222" height="142" />[/code]

Author’s gravatar author

If I click the link you’ve just gave I get the image with no errors.

Author’s gravatar

Yes, that’s because i reverted to the default timthumb until we can fix this

Author’s gravatar author

Ahhh. Makes sense. Other than that the document path is incorrect I can’t think of anything else. However if the document path was wrong GD wouldn’t work either. 🙁

I should be able to try imagemagicking the new timthumb in a day or two. Got the guys in to install a new boiler tomorrow so I won’t be around much.

Author’s gravatar

[code]define (‘CACHE_SIZE’, 250); // number of files to store before clearing cache
define (‘CACHE_CLEAR’, 5); // maximum number of files to delete on each cache clear
define (‘CACHE_USE’, TRUE); // use the cache files? (mostly for testing)
define (‘VERSION’, ‘1.19’); // version number (to force a cache refresh)
define (‘DIRECTORY_CACHE’, ‘./cache’); // cache directory
define (‘MAX_WIDTH’, 1000); // maximum image width
define (‘MAX_HEIGHT’, 1000); // maximum image height
define (‘ALLOW_EXTERNAL’, FALSE); // allow external website (override security precaution)
define (‘MAGIC_PATH’, ‘usr/bin/convert’); // path to imagemagick’s convert[/code]
just added it. still not working
http://pastebin.com/qPt6Jd8w

im getting Parse error: syntax error, unexpected $end in /home/danny/public_html/wp-content/themes/nyb/scripts/timthumb.php on line 688

Reply
Author’s gravatar

Great walkthrough! Really looking forward to the new edits to make this work with the new timthumb.

Reply
Author’s gravatar

Any luck with the new version?

Reply
Author’s gravatar author

Not yet unfortunately. I was getting to it when (don’t know if you saw the msg) my computer failed. I’m still trying to get things sorted after rebuilding my computer.

I’ll try to get it done in the next week or so.

Sorry for the delay.

Author’s gravatar author

Hi,

Sorry not yet. Had an influx of work & I’ve been having trouble getting the new timthumb to work with imagemagick properly.

I’ll try and get at least something up once I’ve finished all my client work.

Author’s gravatar author

Hey Danny.

Sorry it took so long, but I’ve updated the post with support for the latest version of timthumb, which as of today is version 1.26.

Let me know how you get on or if it causes you any problems.

Author’s gravatar

Hmmm, maybe it’s because i have the magic path wrong, but i’ve trued both ~/usr/bin/convert and /usr/bin/convert for it and it doesnt work. i’ve double checked my edits
http://d.pr/8iuE
http://pastebin.com/59wxxFq8

Reply
Author’s gravatar

Thanks for the update, Paul! I can confirm it indeed works. Finally, my gallery thumbs are sharp 🙂

Reply
Author’s gravatar author

Good stuff glad to see its not just me its working for. I’m not sure why its not working for Danny. 🙁

Author’s gravatar author

I sent you mine about an hour or so ago. I can’t resend it right now as I’m not as my computer.

Author’s gravatar

Yup, the version you sent me is working, but is there any way to have it crop from the top instead of center?

Author’s gravatar author

Like I said in the rewritten tutorial I haven’t added that option yet. If you want it to be permanent then you just find the gravity center and change it for gravity top.

Author’s gravatar

Thanks!
Weird, when i try ‘$crop = ($zoom_crop) ? “^ -gravity top -extent {$new_width}x{$new_height}” : “”;’ the whole script stops working

Author’s gravatar author

Ahhh sorry about that. It’s not ‘top’, it’s ‘north’. I was doing it from memory, but I’ve just looked at the command list & it’s definitely ‘north’.

Author’s gravatar

I’d need to add something extra to control the quality? i just tried changing the quality to like 10 just to see a change, but that didnt work

Reply
Author’s gravatar author

Yes, you’d need to add in extra code. I didn’t add it in as it was an extra I didn’t need.

ImageMagick uses a different quality system depending on what compression you are using. If you plan to use JPEG then it’s a percentage out of 100 and the flag is -quality 10%.

If you need to be able to change it on the fly the code might look like this (it would replace the same bit shown in the tutorial above):

You would miss it out on the second one as that is for if the file is not a jpeg & the quality system works differently for JPEG-2000 & PNG files.

Hope that helps.

Author’s gravatar

ok, cool. thanks! so replace this bit of code [code]function show_image($src, $mime_type, $cache_dir, $new_width, $new_height, $zoom_crop) {

global $quality;

$cache_file = get_cache_file ($mime_type);

$new_width = is_numeric($new_width) ? $new_width : ‘100’;
$new_height = is_numeric($new_height) ? $new_height : ‘100’;
$crop = ($zoom_crop) ? "^ -gravity north -extent {$new_width}x{$new_height}" : "";

if (strpos ($mime_type, ‘jpeg’) > 1) {
exec(MAGIC_PATH." -limit memory 50mb -limit map 128mb -quality {$quality}% -size {$new_width}x{$new_height} ‘{$src}’ -thumbnail {$new_width}x{$new_height}{$crop} ‘{$cache_file}’");
} else {
exec(MAGIC_PATH." -limit memory 50mb -limit map 128mb -size {$new_width}x{$new_height} ‘{$src}’ -thumbnail {$new_width}x{$new_height}{$crop} ‘{$cache_file}’");
}[/code] and ‘on the fly, meaning [code]<img src="<?php bloginfo(‘template_url’); ?>/scripts/timthumb.php?src=<?php echo video_thumbnail(); ?>&amp;q=10&amp;h=142&amp;w=222" alt="<?php echo (get_post_meta($post->ID, "post-img-alt", true)) ? htmlspecialchars(get_post_meta($post->ID, "post-img-alt", true)) : the_title(); ?>" width="222" height="142" />[/code]?

Author’s gravatar

I got it to work. knocked off a little load time. thanks

Author’s gravatar author

No worries. I’d advise trying to upgrade to the new post thumbnail system. It’s difficult to set up but take a lot of strain off the server. The only problem is if you have PNG thumbnails, apparently, as you know from my comment on Viper007Bond’s site. 😉

Author’s gravatar

i tried that once, but i couldnt control cropping like i wanted to. i think timthumb was faster too

Reply
Author’s gravatar

also, i need it to load the first image in the post and not the ‘post_thumbnail’. i’d use post_thumbnail if it did that. i’m actually using a mix between the two http://pastebin.com/uUL1sSjL

Author’s gravatar author

Yeah, can’t control crop unfortunately. I’m surprised Timthumb was faster though. WordPress only creates the images once at upload. It’s not on-the-fly image generation like Timthumb is!

If Timthumb works best for you though I say stick with it. 😉

Author’s gravatar

No idea why it was faster.
Yup, if you take a look at my site, you’ll see how important crop control is for it

Author’s gravatar author

Yeah, can see why crop control is important. Maybe it should be a WP feature request. I think you can control cropping only of the main featured thumbnail at the moment (using the uploaded). It could be a new feature to specify crop for each uploaded image? Could be awkward to implement though.

Author’s gravatar author

You can only load the image you set as featured using the post thumbnail system that’s true. You can create lots of different thumbnail sizes though without the need for on-the-fly generation, which is why I like it.

There is a way around the feature image thing, you can use The Attached Image plugin (shameless plug of my own plugin, I know) to grab the first image from a post, even of a custom thumbnail.

Author’s gravatar author

Like I said though, if Timthumb works best then I’d stick with it. 😉

I’m moving to the WP thumbnail system as soon as I can figure out why my PNGs won’t rebuild their thumbnails. Mainly because I’m having a redesign soon so I want to switch over now & get any bugs out the way ready for the redesign.

Author’s gravatar

So youre saying to combine ‘The Attached Image’ and post_thumbnail somehow? do you have skype or are you on Freenode #wordpress?

Author’s gravatar author

Yep that’s right.

Unfortunately I don’t have either. I don’t use IRC and Skype has hated my computer since I upgraded. 🙁

Basically you open an image tag and call the attached image with the image tag option set to false and the image size set to the name of the thumbnail you want which matches what you used when creating your add_image_size functions.

That should be all you need. Works great on here, just I can’t get those PNGs resized so I can’t used it properly yet.

Author’s gravatar

Using the attached image plugin and the post thumbnail here. see the huge difference in quality and the fact that the cropping location is horrible? i need it to crop from the top http://d.pr/pK21 vs http://d.pr/REK0

Author’s gravatar

Gotcha. i think the default crop control for WP is in the core files, so i’d have to setup a custom function in my theme’s functions to control where/how it crops? Maybe you can post a tutorial? Bro, install a forum. you’d get tons of posts

Reply
Author’s gravatar author

I’m busy with a redesign so I might integrate bbPress with the new design (integrates with WP).

It’s not really possible to override the WP core resizing function. There are no hooks, filters or anything in that part of the WP core. The only way to do it is to comment out the function in the file & create your own in your themes function file.

When you upgrade it gets cancelled out though. Looks like Timthumb is the only way until WP comes up with a neat way to control cropping on a per thumbnail basis. 🙁

Author’s gravatar

I made two suggestions in wordpress’ ‘suggestion box’. i doubt they’ll listen

Author’s gravatar author

😆 Never know. Miracles can happen. Like me figuring out why PNGs weren’t being resized, my site no longer uses timthumb. 🙂

Turns out the site was resizing the PNG files correctly. A mistype in the functions file wasn’t showing up in the WP editor, when I downloaded it & opened it in Notepad++ there was a space where the shouldn’t have been and once it was removed everything worked. Still mystified by it, but it works now.

Author’s gravatar

Cool cool. So you’re fine with GD thumbnails and middle cropping?

Author’s gravatar author

Yeah it works well for my site since I custom make my thumbnails square anyway. I can see how It’s not right for your site though. Also the images I upload here are small enough for GD to handle so that doesn’t really matter for my site.

Author’s gravatar

This looks fantastic, any chance of updating it for the current version 2.8.10 of timthumb?

Reply
Author’s gravatar author

Hi,

Thanks Sergio. Unfortunately not in the foreseeable future. Timthumb was completely rewritten after that big security flaw was revealed & I don’t really use it much any more. I tend to share bits of code I do for my work since I don’t get much free time, since my clients don’t use it much any more I haven’t had a need to do the modification to the newer versions. Sorry. 🙁

Older Comments
Newer Comments

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.

I'll keep your WordPress site up-to-date and working to its best.

Find out more