TimThumb upscale fix: stop timthumb from upscaling small images

TimThumb is hosted on http://code.google.com/p/timthumb/, more documentation on the website of the author BinaryMoon.
I had problem with TimThumb, first off all with my multisite but i found a nice fix written by my Dutch colleagues on http://www.letuslook.nl/how-to-make-timthumb-work-in-wordpress-multisite/.

Then TimThumb was scaling up my small images!

I searched for a couple of hours for a fix but no good results. The only interesting result I found was about the same issue I had (over here). In the issue they refered to an older version of TimThumb which is located here (#69). Well with that version i was capable of fixing my upscaling problem.

The upscaling fix

On line 119 of the current TimThumb you will find:

// generate new w/h if not provided
if ($new_width && !$new_height) {
    $new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
    $new_width = floor ($width * ($new_height / $height));

I replaced that piece with the older part:

// don't allow new width or height to be greater than the original
if( $new_width > $width ) {
    $new_width = $width;
if( $new_height > $height ) {
    $new_height = $height;
// generate new w/h if not provided
if( $new_width && !$new_height ) {        
    $new_height = $height * ( $new_width / $width );        
} elseif($new_height && !$new_width) {        
    $new_width = $width * ( $new_height / $height );        
} elseif(!$new_width && !$new_height) {        
    $new_width = $width;
    $new_height = $height;        

Well this worked for me! TimThumb works with my WordPress Multisite and TimThumb isn’t scaling up my small images any more. I’m not a real PHP developer (just a frontend-guy) so maybe this fix is not the best but I hope other people can use it.

If someone knows a better fix or can explain me what is going wrong exactly please leave a comment!

3 thoughts on “TimThumb upscale fix: stop timthumb from upscaling small images

  1. I don’t know a better fix and unfortunately can’t explain you anything.

    Just wanted to say thank you! That was just what I was looking for! At first glance it’s working completely fine.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>