To resize a image in PHP you can use the following snippet.

Sample PHP

function ImageResize($imageName, $tempName, $maxWidth, $maxHeight)
{
	$extension = explode(".", $imageName);
	$extension = $extension[count($extension)-1];
 
	if($extension == "jpeg" || $extension == "jpg")
	{
		$image = imagecreatefromjpeg($tempName);
	}
        elseif($extension == "gif")
	{
		$image = imagecreatefromgif($tempName);
	}
	elseif($extension == "png")
	{
		$image = imagecreatefrompng($tempName);
	}
	
	$Width = imagesx($image);
	$Height = imagesy($image);
 
	if($Width <= $maxWidth && $Height <= $maxHeight)
	{
		return $image;
	}
 
	if($Width >= $Height) 
	{
		$newWidth = $maxWidth;
		$newHeight = $newWidth * $Height / $Width;
	}
	else 
	{
		$newHeight = $maxHeight;
		$newWidth = $Width / $Height * $newHeight;
	}
 
	$image2 = imagecreatetruecolor($newWidth, $newHeight);
	imagecopyresampled($image2, $image, 0, 0, 0, 0, floor($newWidth), floor($newWidth), $Width, $Height);
	return $image2; 
}

3 thought on “How to resize a image in PHP”

Leave a Reply