How To Resize an Image in PHP

      No Comments on How To Resize an Image in PHP

Here is a little snippet to resize an image in php. You need to have the GD library installed to use it, but most of the hosting providers have it activated by default:

function resize_image($destFilename, $srcFilename, $xmax, $ymax)
{
	// detect the extension
	$extension = explode(".", $srcFilename);
	$extension = $extension[count($extension)-1];

	// load the image
	if($extension == "jpg" || $extension == "jpeg")
		$srcImage = imagecreatefromjpeg($srcFilename);
	elseif($extension == "png")
		$srcImage = imagecreatefrompng($srcFilename);
	elseif($extension == "gif")
		$srcImage = imagecreatefromgif($srcFilename);
	
	// detect the original size
	$x = imagesx($srcImage);
	$y = imagesy($srcImage);
	
	// if the source image is smaller than the destination return
	if($x <= $xmax && $y <= $ymax)
		return $srcImage;

	if($x >= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	}
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	}
	
	// creates an empty image
	$destImage = imagecreatetruecolor($newx, $newy);

	// copy and resize from the original image
	imagecopyresized($destImage, $srcImage, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);

	return $destImage; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *