Home  |  Journal  |  PHP Image Resizing Function

PHP Image Resizing Function

As speed is paramount to website efficiency, image re-sizing is a useful function for generating cached versions of images. The following allows you to define:-

  • The source file (realpath)
  • A destination filename (realpath)
  • Maximum width (pixels)
  • Maximum height (pixels)

It maintains the aspect ratio and automatically calibrates how to scale down high resolution images to the desired proportion.

 

	public function imageResize($source, $dest, $maxWidth, $maxHeight)
	{
	  $is = getimagesize($source);
	  $fw = (true || $is[0] >= $is[1]) ? $maxWidth : $maxHeight;
	  $fh = (true || $is[0] >= $is[1]) ? $maxHeight : $maxWidth;
	  $orientation = ($is[0] >= $is[1]) ? 0 : 1;

	  $iw = $is[0];
	  $ih = $is[1];
	  $t = 2;

	  if ($is[0] > $fw || $is[1] > $fh)
	  {
		if ($is[0] - $fw >= $is[1] - $fh)
		{
		  $iw = $fw;
		  $ih = ($fw / $is[0]) * $is[1];
		}
		else
		{
		  $ih = $fh;
		  $iw = ($ih / $is[1]) * $is[0];
		}

		$t = 1;
	  }

	  switch ($t)
	  {
		case 1:
		  $src = imagecreatefromjpeg($source);
		  $dst = imagecreatetruecolor( $iw, $ih );
		  imagecopyresampled($dst, $src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1]);
		  return imagejpeg($dst, $dest, 90);
		  break;
		case 2:
		  return copy($source, $dest);
		  break;
		default:
		  return false;
		  break;
	  }
	}
Get in touch

Want to drive growth and create lasting value? Let’s collaborate and elevate your digital presence, turning your vision into reality.

Get in touch with us today!
We care about your success as much as you do!