Recursively image resize in PHP

Posted: October 11, 2011 in PHP
<?php session_start();
	function resizeImage($sourceFile,$destFile,$width = '',$height ='')
	{	
		$proportional = true;
		$output = 'file';
		copy($sourceFile,$destFile);
		
		$file = $destFile;
		if ( $height <= 0 && $width <= 0 ) return false;
	
		# Setting defaults and meta
		$info = getimagesize($file);
		$image = '';
		list($width_old, $height_old) = $info;	
		
		$final_width = 0;
		$final_height = 0;			
		
		$dims = resizeBound($width_old, $height_old,$width,$height);
		$final_height=$dims['height'];
		$final_width=$dims['width'];			
	
		# Loading image to memory according to type
		switch ( $info[2] ) {
		  case IMAGETYPE_GIF: $image = imagecreatefromgif($file); break;
		  case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($file); break;
		  case IMAGETYPE_PNG: $image = imagecreatefrompng($file); break;
		  default: return false;
		}		
		
		# This is the resizing/resampling/transparency-preserving magic
		$image_resized = imagecreatetruecolor( $final_width, $final_height );
		if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
		  $transparency = imagecolortransparent($image);
	
		  if ($transparency >= 0) {
			$transparent_color = imagecolorsforindex($image, $trnprt_indx);
			$transparency = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
			imagefill($image_resized, 0, 0, $transparency);
			imagecolortransparent($image_resized, $transparency);
		  }
		  elseif ($info[2] == IMAGETYPE_PNG) {
			imagealphablending($image_resized, false);
			$color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
			imagefill($image_resized, 0, 0, $color);
			imagesavealpha($image_resized, true);
		  }
		}
		imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);		   
	
		# Preparing a method of providing result
		switch ( strtolower($output) ) {
		  case 'browser':
			$mime = image_type_to_mime_type($info[2]);
			header("Content-type: $mime");
			$output = NULL;
		  break;
		  case 'file':
			$output = $file;
		  break;
		  case 'return':
			return $image_resized;
		  break;
		  default:
		  break;
		}
		
		# Writing image according to type to the output destination
		switch ( $info[2] ) {
		  case IMAGETYPE_GIF: imagegif($image_resized, $output); break;
		  case IMAGETYPE_JPEG: imagejpeg($image_resized, $output); break;
		  case IMAGETYPE_PNG: imagepng($image_resized, $output); break;
		  default: return false;
		}
		//rename($file,$destFile);
		return true;
	}
	function resizeBound($oldW,$oldH,$newW='',$newH='')
	{		
			if(!($oldW>0 && $oldH>0))
				return;
			$tempW = ( $oldW * $newH ) / ( $oldH ); 
			$tempH = ( $oldH * $newW ) / ( $oldW );
			
			if($newW =="" && $newH != "")
			{
				if($newH >$oldH)
				{
					$dims = resizeBound($oldW, $oldH,'',$oldH);
					$finalH = $dims['height'];
					$finalW = $dims['width'];		
				}
				else
				{
					$finalH = $newH;
					$finalW = $tempW;
				}
			}
			else if($newW !="" && $newH == "")
			{
				if($newW >$oldW)
				{
					$dims = resizeBound($oldW, $oldH,$oldW,'');
					$finalH = $dims['height'];
					$finalW = $dims['width'];		
				}
				else
				{
					$finalH = $tempH;
					$finalW = $newW;
				}
			}
			else if($newW !="" && $newH != "")
			{		
				if($tempW > $newW)
				{
					if($newW >$oldW)
					{
						$dims = resizeBound($oldW, $oldH,$oldW,'');
						$finalH = $dims['height'];
						$finalW = $dims['width'];		
					}
					else
					{
						$finalH = $tempH;
						$finalW = $newW;
					}
				}
				else
				{
					if($newH >$oldH)
					{
						$dims = resizeBound($oldW, $oldH,'',$oldH);
						$finalH = $dims['height'];
						$finalW = $dims['width'];		
					}
					else
					{
						$finalH = $newH;
						$finalW = $tempW;
					}
				}			
			}		
			$dims['height'] = $finalH;
			$dims['width'] = $finalW;
			return $dims;
		}
	function getExtension($filename)
	{
		return end(explode('.', $filename));
	}	
	if(isset($_POST['act']) && $_POST['act']=='resize')
	{
		$source = $_POST['source'];
		$destination = $_POST['destination'];
		$width = $_POST['width'];
		$height = $_POST['height'];
		$source = rtrim(trim($source),'\\');
		$source = rtrim(trim($source),'/');
		$destination = rtrim(trim($destination),'/');
		$destination = rtrim(trim($destination),'\\');


		if($source=="" || $destination=="" || $width=="" || $height=="")
		{
			$_SESSION['msg'] = "Please enter all values.";
			header("location:resize.php");
			exit;
		}
		if(!file_exists($source))
		{
			$_SESSION['msg'] = "Source folder doesn't exist.";
			header("location:resize.php");
			exit;
		}
		if(!file_exists($destination))
		{
			$_SESSION['msg'] = "Destination folder doesn't exist.";
			header("location:resize.php");
			exit;
		}
		echo "<h2>Resize : $width X $height <br />From : $source<br />To : $destination </h2>";
		if($handle = opendir($source)) 
		{
			while (false !== ($file = readdir($handle))) 
			{
				$ext = strtolower(getExtension($file));
				if ($file != "." && $file != ".." && ($ext=='jpg' || $ext=='gif' || $ext=='png' || $ext=='jpeg')) 
				{
					resizeImage($source.'/'.$file,$destination.'/'.$file,$width,$height);
					echo "$file<br />";
				}
			}
			closedir($handle);
		}
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form name="frm" id="frm" method="post">
<input type="hidden" name="act" value="resize" />
<table width="500" border="0" align="center" cellpadding="3" cellspacing="3">
  <? if(isset($_SESSION['msg'])){ ?>
  <tr>
    <td colspan="2" style="color:#C00;"><?=$_SESSION['msg'];?></td>
    </tr>
   <? 
   		unset($_SESSION['msg']);
   } ?>
  <tr>
    <td>Source Folder :</td>
    <td><input type="text" name="source" style="width:300px;" id="textfield" /></td>
  </tr>
  <tr>
    <td>Destination Folder :</td>
     <td><input type="text" name="destination" style="width:300px;" id="textfield" /></td>
  </tr>
  <tr>
    <td>Width :</td>
    <td><input type="text" name="width" id="textfield" /></td>
  </tr>
  <tr>
    <td>Height :</td>
     <td><input type="text" name="height" id="textfield" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="button" id="button" value="Submit" /></td>
  </tr>
</table>
</form>
</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s