Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5120
  • Last Modified:

PHP -- HOw to Resize a JPG Image proportionately on upload function..

Hello,
I have PHP script that resizes a JPG image (from an upload function)

However, the script that I have DOES NOT resize the image PROPORTIONANTLEY,  (sorry for spelling ;) )

The script i have attached resizes the image to a height of 100 pixels.  and it changes the width to 500.. (for some reason, but i do not see the variable in the PHP script,, i only see the HEIGHT of 100 variable)

What is needed to be changed to create a proportionate resize of 400 x 300.?

Anybody have an idea?

Cheers
<?php
// include the Database classes
require_once('classes/database_php4.php');
 
// escape quotes and apostrophes if magic_quotes_gpc off
if (!get_magic_quotes_gpc()) {
  foreach($_POST as $key=>$value) {
    $temp = addslashes($value);
    $_POST[$key] = $temp;
    }
  }
 
$db = new Database('db704.perfora.net','dbo277201649','Ycd2sZaR','db277201649');
$numrows = 1;
// if more than 3 send error message //
if ($numrows > 2) {
  $maxwishes = 'Personal Upload Limit Reached for Today... Sorry';
  echo 'duplicate=y&message='.urlencode($maxwishes);
  }
else {
		function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  // open the directory
  $dir = opendir( $pathToImages );
 
  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {
      echo "Creating thumbnail for {$fname} <br />";
 
      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );
 
      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );
      $new_height = 100;
 
      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );
      srand(time());
      $random = (rand()%999);
      $random2 = (rand()%999);
 
      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
      $newname = 'cmsnewsv2'.$random.$random2.'.jpg';
      $_POST['new_name'] = $newname;
 
      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$newname}" );
      unlink($tmp_img, "{$pathToimages}{$fname}");
      $tmp_img = "";
      $img = "";
      $info = "";
      $fname = "";
    }
  }
  // close the directory
  closedir( $dir );
}
createThumbs("files/","files/thumbs/",500);
  $sql = 'INSERT INTO cmsnewsv2 (story_title,story_body,story_date,story_postedby,story_photo,story_link,story_price)
          VALUES ("'.$_POST['ttitle'].'","'.$_POST['story'].'","'.$_POST['date'].'","'.$_POST['author'].'","'.$_POST['new_name'].'","'.$_POST['uurl'].'","'.$_POST['pprice'].'")';
 
	$result = $db->query($sql);
  if ($result) {
    $created = 'Thankyou!';
    echo 'duplicate=n&message='.urlencode($created);
}
}
?>

Open in new window

0
sam928
Asked:
sam928
  • 3
  • 2
  • 2
1 Solution
 
Ray PaseurCommented:
Here is an example of how to do it.  Please read it over and post back here if you have any questions.  Best regards, ~Ray
<?php // RAY_upload.php UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE
 
 
// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{
 
// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }
 
// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();
 
// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }
 
// RETURN THE VERSION NUMBER
   $gd_version = ereg_replace('[^0-9\.]', '', $gd["GD Version"]);;
   return $gd_version;
}
 
 
// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;
 
// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");
 
// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);
 
// IF NO RESIZING IS NEEDED
   if ($imageX <= $width)
   {
      return FALSE;
   }
 
// THE WIDTH IS TOO GREAT - MUST RESIZE
   $tnailX = $width;
   $tnailY = (int) (($tnailX * $imageY) / $imageX );
 
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}
/* ********************************************************************************************* */
 
 
// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos	= 'photos';
 
// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB
 
// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors	= array(
	0=>"<font color=green>Success!</font>",
	1=>"<font color=gold>The uploaded file exceeds the upload_max_filesize directive in php.ini</font>",
	2=>"<font color=gold>The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form</font>",
	3=>"<font color=gold>The uploaded file was only partially uploaded</font>",
	4=>"<font color=gold>No file was uploaded</font>",
	6=>"<font color=gold>Missing a temporary folder</font>",
	7=>"<font color=gold>Cannot write file to disk</font>"
);
 
// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
	?>
	<h2>Upload Photos</h2>
 
	<!-- ENCTYPE -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="p" value="1" />
	<!-- MAX_FILE_SIZE must precede the file input field -->
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
	<p>
	Find the photo you want to upload and click the "Upload" button below.
	</p>
 
	<table cellpadding="1" cellspacing="1" border="0">
	<tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
	<tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
	&nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
	</table>
	</form>
	<?php
 
	die();
 
} else {
 
// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: Upload Photos</h2>\n";
	echo "<p>\n";
 
// SYNTHESIZE THE NEW FILE NAME
	$f_type	= trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
	$f_name	= trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
	$my_new = getcwd() . '/' . $photos . '/' . $f_name .'.'. $f_type;
	$my_file= $photos . '/' . $f_name .'.'. $f_type;
 
// TEST FOR ALLOWABLE EXTENSIONS
	if ($f_type != 'jpg')
	{
	   die('Sorry, only JPG files allowed');
	}
 
// IF THERE ARE ERRORS
	$error_code	= $_FILES["userfile"]["error"];
	if ($error_code != 0)
	{
		$error_message = $errors[$error_code];
		echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
		die('Sorry');
	}
 
// MOVE THE FILE INTO THE DIRECTORY
	$overwrite	= $_POST['overwrite'];
	$file_size	= number_format($_FILES["userfile"]["size"]);
 
// IF THE FILE IS NEW
	if (!file_exists($my_new))
	{
		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
		{
			$upload_success = 1;
		} else
		{
			$upload_success = -1;
		}
 
// IF THE FILE ALREADY EXISTS
	} else
	{
		echo "<b><i>$my_file</i></b> already exists.\n";
 
// SHOULD WE OVERWRITE THE FILE? IF NOT
		if (empty($overwrite))
		{
			$upload_success = 0;
 
// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
		} else
		{
			$now	= date('Y-m-d');
			$my_bak = $my_new . '.' . $now . '.bak';
			if (!copy($my_new, $my_bak))
			{
				echo "<b>Attempted Backup Failed!</b>\n";
			}
			if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
			{
				$upload_success = 2;
			} else
			{
				$upload_success = -1;
			}
		}
	}
 
// REPORT OUR SUCCESS OR FAILURE
	if ($upload_success == 2) { echo "It has been overwritten.\n"; }
	if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
	if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }
 
	if ($upload_success > 0)
	{
		echo "$file_size bytes uploaded.\n";
		chmod ($my_new, 0755);
	}
 
	echo "</p>\n";
 
// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
	if ($upload_success > 0)
	{
		if ($imageblob	= create_right_size_image($my_new))
		{
			imagejpeg($imageblob, $my_new);
		}
	}
 
	echo "<p><a href=\"$my_file\">See the file</a></p>\n";
 
 
	die('Done');
}
?>

Open in new window

0
 
ErburethCommented:
Commenting out line 43 should do the trick ($new_height = 100;)

on line 42 you already have correct formula to calculate new height, but you overwrite it afterwards, which is bad.
0
 
Ray PaseurCommented:
@Erbureth: Good catch.  After I saw the references to PHP4, I never bothered to read or test the script!

Best to all, ~Ray
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
sam928Author Commented:
Hello, Thank you for the lightning fast responses!!

@Erbureth, i have commented that line out,, and i have checked the result;  

I uploaded a 80 x 60 image... and it converted it to 500 x 375.

---------------------------
soo, somewhere it is resizing the width to 500.  i do not know where,  (is that what  'thumbWidth' is referring to? )   --- line 41 and 42.

i'm confused!


0
 
sam928Author Commented:
... Line 21 also... refers to 'thumbWidth'


0
 
Ray PaseurCommented:
Read over the code I posted in lines 36 to 76.  It tests for appropriate sizes and does not resize images that are already small enough.  Hopefully the comments in that section will be helpful.  Best, ~Ray
0
 
ErburethCommented:
This is because at line 68, you are calling function createThumbs with last parameter 500
If you see the function prototype at line 21, you will see that the last parameter is that thumbWidth, which is desired width of all thumbnails.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now