Thumbnails
Creating a decent thumbnail with PHP and ImageMagick:
function thumbnail($filename, $twidth, $theight) {
$size = getImageSize($filename);
$width = $size[0];
$height = $size[1];$wp = $iwidth / $twidth;
$hp = $iheight / $theight;if ($wp > $hp) {$nw = $width * $hp; $nh = $iheight;}
if ($wp < $hp) {$nh = $height * $wp; $nw = $iwidth;}
exec (“convert -gravity center -crop $nw”
.”x”.”$nh+0+0 $filename thumb.jpg”);
exec (“convert -geometry $twidth”
.”x”.”$theight thumb.jpg thumb.jpg”);
}
First we find out how much we will have to crop from the image so that it keeps the same aspect ratio but still fills all the thumb.
To do this we start by finding out the porportion between the image and the thumbnail in each direction (width and height).
If the porportion is bigger in the width direction then we will have to cut some part of it. The same happens if the porportion is bigger in the height direction.
We now have a image that has the same ratio than the thumbnail we want to generate. So we just have to scale the image to the thumbnail’s size.
Example:
- Original Image Size: 600×500
- Desired Thumbnail Size: 100×125
- Width Porportion: 6
- Height Porportion: 4
First we have to trim the left and right margins so we get the final aspect ratio. To do this we multiply the thumbnail width by 4. Notice that we don’t have to do the same for the height because we would end with the same value.
- New Width: 4 * 100 = 400
- New Height: 500
Now that we have a new image trimmed to the correct aspect ratio we just have to scale the image from 400×500 to 100×125.

