<?php
//get the thumbnail width and length
$widthThumb=$_REQUEST["w"];
$lengthThumb=$_REQUEST["l"];
//get the image source
$filePath=$_REQUEST["fileName"];
//extract the width, length of the image
list($widthImage, $lengthImage, $fileType, $fileAttr) = getimagesize($filePath);
//check if file type if gif(=1), jpg(=2) or png(=3)
//if(($fileType!=1) || ($fileType!=2) || ($fileType!=3)) die("File type should be GIF, JPG, or PNG= ".$fileType.": ".($fileType==1));
//compute the final ratio
$widthRatio=$widthImage/$widthThumb;
$lengthRatio=$lengthImage/$lengthThumb;
if($widthRatio<1)$widthRatio=1;
if($lengthRatio<1)$lengthRatio=1;
if($widthRatio<$lengthRatio)$ratio=$widthRatio;
else $ratio=$lengthRatio;
//compute the thumbnails final dimension and offset on the main image
$widthFinal=$widthThumb*$ratio;
$lengthFinal=$lengthThumb*$ratio;
$offSetX=(int)(($widthImage-$widthFinal)/2);
//$offSetY=(int)(($lengthImage-$lengthFinal)/2);
//we try not to crop from the top
$offSetY=0;
//create the image instances
switch ($fileType){
case 1:
$srcImg= imagecreatefromgif("$filePath");
break;
case 2:
$srcImg=imagecreatefromjpeg("$filePath");
break;
case 3:
$srcImg=imagecreatefrompng("$filePath");
break;
}
$destImg = imagecreatetruecolor($widthFinal, $lengthFinal);
//copy the image
imagecopy($destImg, $srcImg, 0, 0, $offSetX, $offSetY, $widthFinal, $lengthFinal);
//generate the thumbnail
$thumbImg=imagecreatetruecolor($widthThumb, $lengthThumb);
imagecopyresized($thumbImg, $destImg, 0, 0, 0, 0, $widthThumb, $lengthThumb, $widthFinal, $lengthFinal);
//output the image in png format
header('Content-Type: image/png');
imagepng($thumbImg);
//free the resourcses
imagedestroy($thumbImg);
imagedestroy($destImg);
imagedestroy($srcImg);
?>