Luutaa Technologies - Developer Blog

Image Resize in PHP

Today i am working on a PHP project and i needed a PHP function which dynamically resize uploaded image. I searched in Google and other PHP forum for 2 – 3 hours but didn’t find any perfect solution for my need , some of the functions can resize only jpeg images while some of the functions may resize png and gif images also but the output result is jpeg. So i decided to wrote a class for image resize .

This class is very easy to use and interesting thing about this class is it can resize all of the popular formats such as JPEG|JPG|PNG|GIF.

Some of the benefits of this class is described below :

  • The format of the output image is same as of the format of the input image .
  • This class will output transparent compressed png image with the possible quality for web and same for gif format .
  • Another great feature of this class is that, if we cannot pass new width and new height for resize it will automatically calculate it.
  • Name of the output image is in the format of current timestamp + new width + new height + extension, so that the name of the image is always unique.

So , here is the PHP class which do all of the above functionality

<?php
class resizeImage{

	function do_resize($w,$h,$filename=array(),$savepath)
	{

		//get the filename of the image
		$name = $filename['name'];

		//get the extension of the image

		$extension = strtolower(end(explode(".",$name)));

		// check wether supported files were uploaded or not
		if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
		{
			echo ' Unsupported File';
		}
		else
		{
			// get the temporary filename of the image
			$tmpname=$filename['tmp_name'];

			// set the name of the resized image which is "[current timestamp][-][defined width][defined height][extension]"
			$newf=time()."-".$w.$h.".".$extension;

			// check the format and apply php function
			if($extension=="jpg" || $extension=="jpeg" )
			{
				$im = imagecreatefromjpeg($tmpname);
			}
			else if($extension=="png")
			{
				$im = imagecreatefrompng($tmpname);
			}
			else if($extension=="gif")
			{
				$im = imagecreatefromgif($tmpname);
			}

			// $W is original width of the image
			// $H is original height of the image
			// $w is given width of the image
			// $h is given height of the image

			$W=imagesx($im);
			$H=imagesy($im); 

			if($w==0)
			{
				$w = ($W/$H) *$h;
			}
			else if($h==0)
			{
				$h = ($H/$W) * $w;
			} 

			// variable declared for calculation of width and height of the image
			$newH=0;
			$newW=0;

			if($W>$w)
			{
				if($H>$h)
				{
					if(($H/$h)>($W/$w))
					{
						$newH=$h;
						$newW=$h*($W/$H);
					}
					else
					{
						$newW=$w;
						$newH=$w*($H/$W);
					}
				}
				else
				{
					$newW=$w;
					$newH=$w*($H/$W);
				}
			}
			else
			{
				if($H>$h)
				{
					$newH=$h;
					$newW=$h*($W/$H);
				}
				else
				{
					 $newH=$H;
					 $newW=$W;
				}
			}

			// new temporary file is generated width new width and new height
			$new_temp_image  = imagecreatetruecolor($newW, $newH);

			imagecopyresampled($new_temp_image, $im, 0, 0, 0, 0, $newW, $newH, $W, $H);

			if($extension=="jpg" || $extension=="jpeg" )
			{
				// imageinterlace is used for generating progressive image
				imageinterlace($new_temp_image, true);

				// finally create a new resized image
				imagejpeg($new_temp_image,$savepath.$newf,65);

			}
			else if($extension=="png")
			{
				// Turn off transparency blending
				imagealphablending($new_temp_image, false);

				// create a new transparent color for png image
				$color = imagecolorallocatealpha($new_temp_image, 0, 0, 0, 127);

				// completely fill the background of the new image with allocated color from above step.
				imagefill($new_temp_image, 0, 0, $color);

				// again restore transparency blending
				imagesavealpha($new_temp_image, true);

				// finally create a new resized image
				imagepng($new_temp_image,$savepath.$newf,9);

			}
			else if($extension == "gif" )
			{

				// set the transpatent color in the given image
				$tranparent = imagecolortransparent($im);

				  // check if we have a specific transparent color
				  if ($tranparent >= 0) {

						// get the original rgb value
						$transparent_color    = imagecolorsforindex($im, $tranparent);

						// Allocate the same color in the new image resource
						$tranparent    = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);

						// fill the background of the new image with allocated color.
						imagefill($new_temp_image, 0, 0, $tranparent);

						// Set the background color for new image to transparent
						imagecolortransparent($new_temp_image, $tranparent);
				   }

				imagegif($new_temp_image,$savepath.$newf);
			}

			imagedestroy($new_temp_image);

			// after success this class returns the name of the new file
			return $newf;
		}
	}
}
?>

I know some of you are bit confused by this class, so let me explain step by step.First we declared a class named resizeImage and in this class we create our function named do_resize().

As you can we are passing four parameters in this function :

– width of the new image

– height of the new image

– array of the $_FILES[‘input_name’]

– savepath (where you want to save the resized image)

<?php

class resizeImage{

	function do_resize($w,$h,$filename=array(),$savepath)
	{
        }
}
?>

Next, we are defining some variables such as :

– original name of the image

– temporary name of the image

– format of the image

then we wrote a code block which checks the format of the code and if supported format not found we echoed “Unsupported File Format”

//get the filename of the image

$name = $filename['name'];

// get the temporary filename of the image
$tmpname=$filename['tmp_name'];

//get the extension of the image
$extension = strtolower(end(explode(".",$name)));

// check wether supported files were uploaded or not
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
	echo ' Unsupported File Format';
}

After checking the format of the code we move a step ahead,

if the given format is correct we create new name for our final output image

in a way, that it should always be unique, so we do this in this way :

current timestamp + new width + new height + format of the original image.

After that we put PHP if else and applied proper image create funtion for correct format

// set the name of the resized image which is "[current timestamp][-][defined width][defined height][extension]"
$newf=time()."-".$w.$h.".".$extension;

// check the format and apply php function
if($extension=="jpg" || $extension=="jpeg" )
{
	$im = imagecreatefromjpeg($tmpname);
}
else if($extension=="png")
{
	$im = imagecreatefrompng($tmpname);
}
else if($extension=="gif")
{
	$im = imagecreatefromgif($tmpname);
}

Next, we are going to calculate the width and height for the new image
before i can explain further please look at the variable declaration :
$W – indicates original width of the image
$H – indicates original height of the image
$w – indicates width which we pass it to our function
$h – indicates height which we pass it to our function
$newW – indicates width which we are going to calculate
$newH – indicates height which we are going to calculate
first we check wether new width of new height is given or not,
if not we can calculate it too.

$W=imagesx($im);
$H=imagesy($im); 

if($w==0)
{
	$w = ($W/$H) *$h;
}
else if($h==0)
{
	$h = ($H/$W) * $w;
} 

// variable declared for calculation of width and height of the image
$newH=0;
$newW=0;

Next, we are going to calculate the new height and new width of the image

if($W>$w)
{
	if($H>$h)
	{
		if(($H/$h)>($W/$w))
		{
			$newH=$h;
			$newW=$h*($W/$H);
		}
		else
		{
			$newW=$w;
			$newH=$w*($H/$W);
		}
	}
	else
	{
		$newW=$w;
		$newH=$w*($H/$W);
	}
}
else
{
	if($H>$h)
	{
		$newH=$h;
		$newW=$h*($W/$H);
	}
	else
	{
		 $newH=$H;
		 $newW=$W;
	}
}

first we check whether original image is greater than the given image, if it
is greater than given image, we further check whether original height is greater
than given height, if it is greater than given image, than we check if height is greater
than width than new height will be given height in the function and new width will be given
height * (original width/ original height) and if height is not greater than width, than new
width will be the given width and new height will be given width * (original height / original
width), else original height is not greater than given height, new width will be given width and
new height will be given width * (original height / original width), if outermost if condition
failed than we will process in else condition, in this else block we will check if original height
is greater than given height or not, if TRUE, than new height will be given height and new width
will be given height * ( original width / original height), if FALSE, new height will be original
height and new width will be original width
After calculating new width and new height for the image, we will collect an
image resource identifier with the help of PHP function imagecreatetruecolor
with the help of which we would proceed further and resize our image with the help
of another function imagecopyresampled

// new temporary file is generated width new width and new height
$new_temp_image  = imagecreatetruecolor($newW, $newH);

imagecopyresampled($new_temp_image, $im, 0, 0, 0, 0, $newW, $newH, $W, $H);

Next, we are going to produced our final image and we will do that with the

help of image resource identifier returned by the above function by checking the

format of the image

if($extension=="jpg" || $extension=="jpeg" )
{
	// imageinterlace is used for generating progressive image
	imageinterlace($new_temp_image, true);

	// finally create a new resized image
	imagejpeg($new_temp_image,$savepath.$newf,65);

}
else if($extension=="png")
{
	// Turn off transparency blending
	imagealphablending($new_temp_image, false);

	// create a new transparent color for png image
	$color = imagecolorallocatealpha($new_temp_image, 0, 0, 0, 127);

	// completely fill the background of the new image with allocated color from above step.
	imagefill($new_temp_image, 0, 0, $color);

	// again restore transparency blending
	imagesavealpha($new_temp_image, true);

	// finally create a new resized image
	imagepng($new_temp_image,$savepath.$newf,9);

}
else if($extension == "gif" )
{

	// set the transpatent color in the given image
	$tranparent = imagecolortransparent($im);

	// check if we have a specific transparent color
        if ($tranparent >= 0) {

	       // get the original rgb value
	       $transparent_color    = imagecolorsforindex($im, $tranparent);

        	// Allocate the same color in the new image resource
        	$tranparent    = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);

        	// fill the background of the new image with allocated color.
        	imagefill($new_temp_image, 0, 0, $tranparent);

        	// Set the background color for new image to transparent
        	imagecolortransparent($new_temp_image, $tranparent);
        }

	imagegif($new_temp_image,$savepath.$newf);
}

Next, we are going to destroy our temporary image resource identifier because we didn’t

need it any more .
Finally, our function will return the name of the uploaded image

imagedestroy($new_temp_image);

// after success this class returns the name of the new file
return $newf;

That’s all. Hope you enjoyed this tutorial and may this class will help you in your own project.
Any feedback and suggestion are welcome from you. We would like to hear from you.

Leave a Reply:

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