PHP image thumbnails

I mentioned in a post yesterday that I also use PHP to generate image thumbnails. The idea is that any new photos I simply upload to the BMTG site, with a Picasa caption attached, and the site should do the rest.

Thumbnails are generated on-the-fly but only once as, once created, they are saved and re-used.

if (!file_exists($thumb_filename)) {

   $src_img=imagecreatefromjpeg($full_filename);
   $old_x=imageSX($src_img);
   $old_y=imageSY($src_img);

   $new_w=round(($old_x/$old_y)*100);
   $new_h=100;

   $dst_img=ImageCreateTrueColor($new_w,$new_h);
   imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,$old_x,$old_y);
   imagejpeg($dst_img,$thumb_filename);
   imagedestroy($dst_img);
   imagedestroy($src_img);
}

$thumb_filename should contain the filename of the thumbnail and $full_filename is the filename of the original image (that the thumbnail is taken from). In the case of this example I’m creating thumbnails that have a height of 100 pixels and maintain their ratio, hence the width is variable.

The above can be made a lot more compact, but I’ve expanded it out to make it easier to follow.

By the time the code has finished, if the thumbnail didn’t already exist, it now does. Make sure the folder that the thumbnails are stored in has the appropriate permissions though!

Leave a comment

Talk to me!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll Up
%d bloggers like this: