NYCPHP Meetup

NYPHP.org

[nycphp-talk] Creatings Thumbnails with GD

Dan Cech dcech at phpwerx.net
Wed Nov 23 14:47:21 EST 2005


Jeff Loiselle wrote:
> I am working on a new project, which is hosted on a server w/o
> ImageMagick (^@#%#^).. So I am forced to use GD to create
> thumbnails... Anyone got any examples? Jeff Knight are you out there?
> ;-) Anyone? Bueller? Bueller?

If you prefer your thumbnails to always have a consistent height and 
width (for example if you use floats to create liquid thumbnail pages) 
you may find this useful.

Dan

define('THUMB_BG_R',  255);
define('THUMB_BG_G',  255);
define('THUMB_BG_B',  255);

function _thumbnail_image_gd2($imgfile,$w = NULL,$h = NULL,$format = 
'png',$destfile = NULL)
{
   $size = getimagesize($imgfile);
   $s_w = $size[0];
   $s_h = $size[1];

   $w_ratio = $w / $s_w;
   $h_ratio = $h / $s_h;

   // source image is smaller than dest image
   if (min($h_ratio,$w_ratio) >= 1) {
     $d_w = $s_w;
     $d_h = $s_h;
     $d_x = floor(($w - $s_w) / 2);
     $d_y = floor(($h - $s_h) / 2);
   // same aspect ratio
   } elseif ($w_ratio == $h_ratio) {
     $d_w = $w;
     $d_h = $h;
     $d_x = 0;
     $d_y = 0;
   // different aspect ratio
   } elseif ($w_ratio < $h_ratio) {
     $d_w = $w;
     $d_h = floor($s_h * $w_ratio);
     $d_x = 0;
     $d_y = floor(($h - $d_h) / 2);
   } else {
     $d_w = floor($s_w * $h_ratio);
     $d_h = $h;
     $d_x = floor(($w - $d_w) / 2);
     $d_y = 0;
   }

   switch ($size[2]) {
     case 1: // GIF
       $src = imagecreatefromgif($imgfile);
       break;
     case 2: // JPEG
       check_jpeg($imgfile);
       $src = imagecreatefromjpeg($imgfile);
       break;
     case 3: // PNG
       $src = imagecreatefrompng($imgfile);
       break;
     default:
       $src = imagecreatefromstring(file_get_contents($imgfile));
   }

   if (!is_resource($src)) {
     return false;
   }

   $dest = imagecreatetruecolor($w,$h);
   if (!is_resource($dest)) {
     return false;
   }

   imageantialias($dest,TRUE);

   $bg = imagecolorallocate($dest,THUMB_BG_R,THUMB_BG_G,THUMB_BG_B);
   imagefill($dest,0,0,$bg);

   imagecopyresampled($dest,$src,$d_x,$d_y,0,0,$d_w,$d_h,$s_w,$s_h);

   if (isset($destfile)) {
     switch (strtolower($format)) {
       case 'jpg':
       case 'jpeg':
         imagejpeg($dest,$destfile);
         break;
       case 'png':
         imagepng($dest,$destfile);
         break;
       default:
         return false;
     }
   } else {
     switch (strtolower($format)) {
       case 'jpg':
       case 'jpeg':
         imagejpeg($dest);
         break;
       case 'png':
         imagepng($dest);
         break;
       default:
         return false;
     }
   }

   return true;
}



More information about the talk mailing list