// If we chose to scale down the image, we will// need to get the original image propertions

$iOrigWidth = imagesx($img);$iOrigHeight = imagesy($img);

if ($sType == 'scale') {

// Get scale ratio

$fScale = min($iMaxWidth/$iOrigWidth,$iMaxHeight/$iOrigHeight);

// To explain how this works, say the original// dimensions were 200x100 and our max width// and height for a thumbnail is 50 pixels.// We would do $iMaxWidth/$iOrigWidth// (50/200) = 0.25// And $iMaxHeight/$iOrigHeight// (50/100) = 0.5

// We then use the min() function// to find the lowest value.

// In this case, 0.25 is the lowest so that// is our scale. The thumbnail must be// 1/4th (0.25) of the original image

if ($fScale < 1) {

// We must only run the code below// if the scale is lower than 1// If it isn't, this means that// the thumbnail we want is actually// bigger than the original image

// This works similarly to other one but// rather than the lowest value, we need// the highest. For example, if the// dimensions were 200x100 and our thumbnail// had to be 50x50, we would calculate:// $iThumbnailWidth/$iOrigWidth// (50/200) = 0.25// And $iThumbnailHeight/$iOrigHeight// (50/100) = 0.5

// We then use the max() function// to find the highest value.

// In this case, 0.5 is the highest so that// is our scale. This is the first step of// the image manipulation. Once we scale// the image down to 0.5, it will have the// dimensions of 100x50. At this point,// we will need to crop the image, leaving// the height identical but halving// the width to 50

// Our $tmpimg will now have the scaled down// image. The next step is cropping the picture to// make sure it's exactly the size of the thumbnail

// The following logic choose how the image// will be cropped. Using the previous example, it// needs to take a 50x50 block from the original// image and copy it over to the new thumbnail

// Since we want to copy the exact center of the// scaled down image, we need to find out the x// axis and y axis. To do so, say the scaled down// image now has a width of 100px but we want it// to be only 50px

// Somehow, we need to select between the 25th and// 75th pixel to copy the middle.

// To find this value we do:// ($iNewWidth/2)-($iThumbnailWidth/2)

// ( 100px / 2 ) - (50px / 2)// ( 50px ) - ( 25px )// = 25px

if ($iNewWidth == $iThumbnailWidth) {

$yAxis = ($iNewHeight/2)-($iThumbnailHeight/2);$xAxis = 0;

} else if ($iNewHeight == $iThumbnailHeight) {

$yAxis = 0;$xAxis = ($iNewWidth/2)-($iThumbnailWidth/2);

}

// We now have to resample the new image using the// new dimensions are axis values.