Make image version

17 Ⅴ 2010

This is a function I use to make multiple versions such as thumbnails of uploaded images.
There’s three methods for resizing available in it (mask, fit & limit).

 // Function for making a new resized copy of a file
// mask makes the shortest edge match the mask, so it will be bigger than the mask, always resizes!
// fit makes the longest edge match, always resizes!
// limit makes the image fit, but won't stretch if it's smaller.
function makeImageVersion($newWidth, $newHeight, $filePath, $newName, $fileExtension, $method){

	// Find out the original size of the image
	list($wO, $hO) = getimagesize($filePath);
	
	// Get the ratios it would take to resize
	$wR = $newWidth / $wO;
	$hR = $newHeight / $hO;
	
	// Figure out which ratio we need
	switch($method){
		case 'mask':
			if($wR > $hR){ $ratio = $wR; }
			else{ $ratio = $hR; }
			break;
		case 'limit':
			if($wR < 1 && $wR < $hR){ $ratio = $wR; }
			elseif($hR < 1){ $ratio = $hR; }
			else{ $ratio = 1; }
			break;
		case 'fit':
		default:
			if($wR > $hR){ $ratio = $hR; }
			else{ $ratio = $wR; }
			break;
	}

	$wN = round($wO * $ratio);
	$hN = round($hO * $ratio);

	$iP = imagecreatetruecolor($wN, $hN);
	imageAlphaBlending($iP, false);
	imageSaveAlpha($iP, true);

	if($fileExtension == 'jpg'){ $iI = imagecreatefromjpeg($filePath); }
	elseif($fileExtension == 'png'){	$iI = imagecreatefrompng($filePath); }
	else{ $iI = imagecreatefromgif($filePath); }

	imagecopyresampled($iP, $iI, 0, 0, 0, 0, $wN, $hN, $wO, $hO);

	if($fileExtension == 'jpg'){ imagejpeg($iP, $newName, 90); }
	elseif($fileExtension == 'png'){ imagepng($iP, $newName); }
	else{ imagegif($iP, $newName); }
}