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.

This entry was posted on Monday, January 31st, 2005 at 5:52 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Comments

  1. Anonymous says:

    what if you don‘t want to loose content from the image? why not just throw in white margins mimicking the white parts of a kodak instant picture?

    ... on July February 1st, 2005
  2. Andre Restivo says:

    IMHO it doesn‘t look as good.

    ... on July February 1st, 2005
  3. Anonymous says:

    Rule number 5 from Kodak‘s Top 10 Tips for Great Pictures: Move it from the middle. That is why its so difficult to trim pictures without human aid.

    Since you are into pictures you should check out some of Kodak‘s tutorials [http://www.kodak.com/eknec/PageQuerier.jhtml?pq-path=317&pq-locale=en_US]

    cheers

    ... on July February 2nd, 2005

Post a Comment