Help me with the automatic resizing image in PHP

Hi Everybody

My name is Dosso and i am designer.but beginner in web development.i am in learning process of PHP. i am trying to do resize image automatically with php, but it does not work as expected…So really your help by checking my script and tell what is the mistake or if you can give me another working scripts. Thanks is advance, i appreciate your help. i am using script to create a thumbs. i want the script to resize the image in upload process

here is my upload_thumb.php script:

<?php
//define a constant for the maximun file size upload

define (‘MAX_FILE_SIZE’, 51200);

if(array_key_exists(‘upload’, $_POST)) {

//define constant for upload folder or where the folder to retain files exits

define(‘UPLOAD_DIR’, ‘C:/upload_test/’);

// remove all white space in filename and replace by underscore ou hyhen

$file = str_replace(’ ', ‘_’, $_FILES[‘image’][‘name’]);

// convert the maximum size to KB

$max = number_format(MAX_FILE_SIZE/1024, 1). ‘KB’;

//create a array of permitted MIME TYPE

$permitted = array(‘image/png’,‘image/gif’,‘image/jpg’,‘image/jpeg’,‘image/pjep’);

//replace any spaces in the filename with underscrores

$file =str_replace(’ ', ‘_’, $file);

// begin to assume that the file is unacceptable

$sizeOK = false;
$typeOK = false;

// check that file within the restricted size permitted

if($_FILES[‘image’][‘size’]> 0 || $_FILES[‘image’][‘size’] <= MAX_FILE_SIZE) {

$sizeOK = true;
}

// check that the file is among the permitted MIME

foreach ($permitted as $type) {
if($type == $_FILES[‘image’][‘type’]) {

 $typeOK = true;

 break;

 }

}

if ($sizeOK && $typeOK) {

 switch($_FILES['image']['error']) {

  case 0:

	include('../includes/create_thumb.inc.php');
	
	 break;

case 3:
$result= “Error uploading file. Please try again.”;
default:
$result= “System error uploading $file. Contact webmaster.”;
}
}

elseif ($_FILES[‘image’][‘error’] == 4) {
$result= ‘No file selected’;
}
else {
$result = “$file cannot be uploaded. Maximun size: $max.
Acceptable file types: gif, jpg, png.”;
}
}

?>

<!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>upload test</title>
</head>

<body>
<?php
// if the form has been submitted, display answer

if (isset($result)) {
echo ‘<ol>’;
foreach ($result as $item) {
echo “<p><strong><li>$item</li></strong></p>”;
}
echo ‘<ol>’;
}

?>
<form action=“” method=“post” enctype=“multipart/form-data” name=“uploadImage” id=“uploadImage”>
<p>
<label for=“image”>File 1:</label>

<input type=“hidden” name=“MAX_FILE_SIZE” value=“<?php echo MAX_FILE_SIZE; ?>” />

<input type=“file” name=“image” id=“image” />
</p>

<p>
<input type=“submit” name=“upload” id=“upload” value=“upload” />
</p>
</form>

</body>
</html>

Now here is the script for the resize automatically,this script is a separate folder and i use include to put in the upload scrit :

<?php

// define constant
define(‘THUMB_DIR’, ‘C:/upload_test/thumbs/’);
define(‘MAX_WIDTH’, 120);
define(‘MAX_HEIGHT’, 90);

  // abandon proccessing if no image selected

  if (is_uploaded_file($_FILES['image']['tmp_name'])) {
	
	 $original = $_FILES['image']['tmp_name'];
	
	// begin by getting the details of the original
	
	list($width,$height,$type) = getimagesize($original);
	
	// calculate the ratio
	
	 if($width &lt;= MAX_WIDTH && $height &lt;= MAX_HEIGHT) {
		
	  $ratio = 1;
	 }
	
	  elseif ($width &gt; $height) {
		
		  $ratio = MAX_WIDTH/$width;
	  }
	   else {
		
		  $ratio = MAX_HEIGHT/$height;
	   }
	
	   // strip the extension off the image
	
	   $imagetypes = array('/\\.gif$/','/\\.jpg$/','/\\.jpeg$/','/\\.png$/');
	   $name = preg_replace($imagetypes, '', basename($original));
	
	   // create an image resource from the original
	
	    switch ($type) {
		
		  case 1:
		
		   $source = @imagecreatefromgif($original);
		
		   if(!$source) {
			$result ='Cannot the process the GIF file. Please use JPEG or PNG.';
		   }
		    break;
			
			case 2:
			
			 $source = @imagecreatefromjpeg($original);
			break;
			
			case 3:
			
			$source = @imagecreatefrompng($original);
			break;
		   default:
		
		   $source = NULL;
		   $result ='Cannot identify file type.';	
		}
		
		// make sure the file is OK
		
		 if (!$source) {
			
			$result ='Problem copying the original';
		 }
		  else {
			
			// calculate the dimension of the tumbnail
			
			$thumb_width = round($width * $ratio);
			$thumb_height = round ($height * $ratio);
			
			// create an image resource for the thumbnail
			
			$thumb = imagecreatetruecolor ($thumb_width, $thumb_height);
			
			// create the resized of the copy
			
			imagecopyresampled ($thumb, $source, 0,0,0,0, $thumb_width, $thumb_height, $width, $height);
			
			// save the resized copy
			
			 switch ($type) {
				 case 1:
				 if (function_exists('imagegif')) {
					 $success=imagegif($thumb, THUMB_DIR.$name.'_thb.gif');
					 $thumb_name = $name.'_thb.gif';
				 }else {
					
					 $success= imagejpeg($thumb, THUMB_DIR.$name.'_thb.jpg', 50);
					 $thumb_name = $name.'_thb.jpg created';
				 }
				  break;
				
				  case 2:
				
				  $success=imagejpeg($thumb, THUMB_DIR.$name.'_thb.jpg', 100);
				  $thumb_name = $name.'_thb.jpg created';
				
				  break;
				
				  case 3:
				
				  $success =imagepng($thumb, THUMB_DIR.$name.'_thb.png');
				  $thumb_name = $name.'thb.png created';
			 }
			    if ($success) {
					
					 $result = '$thumb_name created';
				}
				 else {
					
					$result = 'Problem creating thumbnail.';
				 }
			// remove the image resources from memory
			
			imagedestroy($source);
			imagedestroy($thumb);
	 }

  }

?>

Your help and assistance will save me…i got this script from a book.

Thanks.

1/ What errors are you getting or what is not happening.

2/ When posting your code here put your php code within the php tags and your other code withing the code tags - available in advanced mode. This makes it easier to read and spot problems.

3/ Are you working on a local computer using something like XAMPP or WAMP?

hi rubble,

I am new on this forum and really know to put the script the php tag. i use wampserver2.2 on my local computer…when i uploaded a big image, it displayed:

“image cannot be uploaded. Maximun size 50.0kb.Acceptable file:gif,jpg,png”

I asked about a local install as this looks a bit strange to me define(‘THUMB_DIR’, ‘C:/upload_test/thumbs/’); I use XAMPP and do not specify a path with C: in it. everything is relative to the folder I am working in.

You are defining your maximium file size here:
define (‘MAX_FILE_SIZE’, 51200);

And are then dividing that by 1024
$max = number_format(MAX_FILE_SIZE/1024, 1). ‘KB’;

This means your maximium file size is 50kb - what was the size of the image you were trying to upload?

HI there,

And thanks again for the help. the file i tried to upload in of 366/768 size.But the script of resizing automatically was suppose to accept the image an then reduce its size to

50kb (That’s is what i wanted to do).

And the part of define (‘THUMB_DIR’, ‘C:upload_test/thumbs/’) is actually the folder on my C where the resized file is supposed to go if the process success.

Thanks again…

If you’re not comfortable with using PHP I would HIGHLY recommend using a image resizing service. One such service in Sencha io src – no programming involved. Merely pass the URL of the image with resizing options. Than you don’t have muddle around with programming which you are obviously not qualified to do in the first place. Keep it simple.


define ('THUMB_DIR', 'C:upload_test/thumbs/')

That is not portable. It will only work on your computer. So when you go to move this to a server it won’t work. Not to mention if anyone else was working on this it probably wouldn’t work for them either unless they created that directory and were on a windows machine. Web sites should always be as portable as possible considering the code base is likely to be used in multiple different environments from a live server to a coworkers own environment.

The proper way would be to define a constant for the web root absolute path. Than define a separate constant or variable concatenating that web root with the location of the image upload directory.

Hi oddz,

Thank you for your reply and advise…But can anyone give me the PHP image automatically upload resizing script please??

I do not think you can resize to a file size automaticaly with GD. You would need to do some calculation with the expected finished dimensions and PPI.

If you used Imagemagick you could ( with a later version ) resize to a file size.