Pass values into a function

Jeff
Jeff used Ask the Experts™
on
I have a photo resize function that I need to be able to pass the width and height values into.
I have tried:
$max_width=600;
$max_height=800;

function create_right_size_image($image, $width=$max_width, $height=$max_height)
{

Didn't work??
function create_right_size_image($image, $width=600, $height=800)
{
// 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 && $imageY <= $height)
   {
      return FALSE;
   }
 
// GET SCALE FACTORS FOR RESIZE
   $scaleX = $height / $imageY;
   $scaleY = $width / $imageX;
 
// THE WIDTH IS TOO GREAT - MUST RESIZE
   if ($scaleY < $scaleX)
   {
      $tnailX = $width;
      $tnailY = (int) ($scaleY * $imageY);
   }
// THE HEIGHT IS TOO GREAT - MUST RESIZE
   else
   {
      $tnailY = $height;
      $tnailX = (int) ($scaleX * $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 ;
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
1.  Are you sure that the photo you are passing in can be seen/read by PHP?
2.  Line 8: you don't need to quote "$image", you can just put $image.
3.  Lines 15-18: If the image is correct then you should return the image not false.  You are returning the image down the line and it makes sense that you would want to keep the image if it was too small, so return it so you can use it otherwise small images will return false when that also corresponds to GD not being available and other problems you wish to check for.

Otherwise I would make sure that the target directories are writable and that PHP can read the source file.
Top Expert 2008

Commented:
You can pass the width and height when you call the function, the default values are 600 and 800. If 600x800 is the size you want, you don't need to use any width/height parameters.
$resized_image = create_right_size_image($image, 300, 400);

Open in new window

Author

Commented:
The uploader works as is. I wold like to use it on seversl sites, thus the need to have the Max Width and Max Height in a variable that I can place in the set-up file for each particular site. Or possible pass the vars in the post.
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Top Expert 2008

Commented:
You can do like this:
# setup file
$max_width=600;
$max_height=800;
 
# using the function
$resized_image = create_right_size_image($image, $max_width, $max_height);

Open in new window

Author

Commented:
This is the error message I get:

Warning: Missing argument 2 for create_right_size_image(), called in /home/tylerweb/public_html/test/upload_final.php on line 131 and defined in /home/tylerweb/public_html/test/uploadfunctions.php on line 38

Warning: Missing argument 3 for create_right_size_image(), called in /home/tylerweb/public_html/test/upload_final.php on line 131 and defined in /home/tylerweb/public_html/test/uploadfunctions.php on line 38

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/tylerweb/public_html/test/uploadfunctions.php on line 78

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/tylerweb/public_html/test/uploadfunctions.php on line 79
Mark BradyPrincipal Data Engineer

Commented:
I have a script that will perform the following.
1: Take an image that is passed to it from a form
2: rename the image to a random number with the correct extention (you can take this out if not needed)
3: Checks to see if image format is jpeg, jpg or gif (only those are allowed but you can change to suit
4: Resizes the image to a value you set in your form (the form sends it through as a hidden field
5: Uploads the new file a server then sends the imagename (the new one) back to the form for display

Here's the code. Feel free to modify it to suit your needs.

<?php  
   //    img.php
             
                    
             $random_digit=rand(0000000,9999999);
       
 if(isset($_POST['submit'])){      // submit is a hidden field on the form
 if (isset ($_FILES['new_image'])){
              $imagename = $_FILES['new_image']['name'];
              $maximum_width = $_POST['max_width'];
              $maximum_height = $_POST['max_height'];
              $ext = substr($imagename, strpos($imagename,'.'), strlen($imagename)-1);
              $ext = strtolower($ext);
                    if($ext == ".jpg" || $ext == ".jpeg" || $ext == ".pjpeg" || $ext == ".gif" || $ext == ".bmp"){
                    $new_name = $random_digit.$ext;
              $imagename = $new_name;
                                      
              $source = $_FILES['new_image']['tmp_name'];
                           
              $target = "uploads/".$imagename;
              move_uploaded_file($source, $target);
 
              $imagepath = $imagename;
              $save = "uploads/" . $imagepath; //This is the new file you saving
              $file = "uploads/" . $imagepath; //This is the original file
 
              list($width, $height) = getimagesize($file) ;
 
              if ($width <= $height) {

$modheight = $maximum_height;            // Change the 350 value to whatever max size/length you would like
$diff = $height / $modheight;
$modwidth = $width / $diff;
} else {
$modwidth = $maximum_width;            // Change the 350 value to whatever max size/length you would like
$diff = $width / $modwidth;
$modheight = $height / $diff;
}

 
              $tn = imagecreatetruecolor($modwidth, $modheight) ;
              $file_type = $_FILES['new_image']['type'];
if($file_type == "image/pjpeg" || $file_type == "image/jpg" || $file_type == "image/jpeg"){
$image = imagecreatefromjpeg($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
              imagejpeg($tn, $save, 100) ;

}elseif($file_type == "image/gif"){
$image = imagecreatefromgif($file);
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
              imagegif($tn, $save, 100) ;
}else{
      
}
          //Send imagename back to Add_items.php for display
           header("Location: add_items.php?imagename=uploads/$imagename");   //change 'add_items.php' to your php upload form
     
          }else{
           header("Location: add_items.php?imagename=1");   // same as above. The imagename=1 tells your upload form there is an attempt to upload a file type other than that allowed above (jpg, jpeg or gif)
                  
            }
        }
        }
   
?>
Top Expert 2008

Commented:
>> Warning: Missing argument 2 for create_right_size_image()

You should not get this warning when the function is defined like you showed in the original post:

function create_right_size_image($image, $width=600, $height=800)

Furthermore, you would not get that warning when you call the function with three parameters, like I showed above:

$resized_image = create_right_size_image($image, $max_width, $max_height);
Top Expert 2008

Commented:
Can you show us line 131 from the file upload_final.php ?
Mark BradyPrincipal Data Engineer

Commented:
Here is my form if you wanted to take a look. Just ignore all the other stuff as it only pertains to my site.

// add_items.php

<?php


// Check to see if user is logged in
if($session->logged_in){

$imagename = $_GET['imagename']; // This is returned in the URL from img.php


echo "<center><table cellpadding=0 cellspacing=0 border=0 width=878>";
echo "<tr><td height=35></td></tr>";
?>

<tr><td valign=top><center><table width=800 border=0 cellpadding=0 cellspacing=3 style="font-family: arial">
<td><img src="php_images/picture_strip.gif"></td>
<?php
// This is where the form goes
?>

<td align=center valign=top><table border=0>

<td align=right valign=top width=220><font face=arial size=2>Upload image :</td><td align=left>
<!-- Image upload form  -->

<form action="img.php" method="post" enctype="multipart/form-data" id="something" class="uniForm">
        <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
        <button name="submit" type="submit" class="submitButton"><font size=2 color=red>Upload Image</button>&nbsp;&nbsp;&nbsp;&nbsp;Jpg - Jpeg and Gig files only
</form>

<?php
if ($imagename == "1"){  // this is sent back from img.php if incorrect file format is uploaded
      echo "<font color=red face=arial size=2>Wrong file type !<br><font color=#000000>Images must be jpg | jpeg | or gif only </td></tr>";
}else{

if ($imagename != ""){
      echo "<img src=".$imagename."></td></tr>";
}else{
      
}
}

// finish off your table or whatever here eg:  </td></table></html>

?>
jeffey48: The reason it is giving that error is because you might be missing an argument.

Check your function if it looks like this:
function create_right_size_image($image, $width=600, $height=800) {
Then the error should not happen unless you called the function like this:
create_right_size_image() <- This would throw a missing argument warning for the first variable since you have not supplied something for it.  The other two variables are pre-defined meaning they assume the value shown above unless the user overrides it.

The second two errors you stated are thrown because the width and height passed into the function are either non-integers, null, or 0.

If your function looks like this:
function create_right_size_image($image, $width, $height) {
Then you must supply three variables each time you call the function:
create_right_size_image('file.jpg', 600, 800);
If you don't call the function as shown one line above then you will get the error messages shown above.
Then everytime

Author

Commented:
The script works perfectly when the function is written ike this:
function create_right_size_image($image, $width=600, $height=800)

Thanks elvin fot the code, but the code I have does exactly what I want it to except I would like to pass the max image size, height and width, as a virable so that I would be able to use this script on multiple sites by passing these variables.


// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
      if ($upload_success > 0)
      {
line 131 >>            if ($imageblob = create_right_size_image($my_new))
            {
                  imagejpeg($imageblob, $my_new, $quality);
            }
      }
FUNCTION - uploadfunctions.php
Works perfectly like this.
<?php
 
// 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=$max_width, $height=$max_height)
function create_right_size_image($image, $width=600, $height=800)
{
// 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 && $imageY <= $height)
   {
      return FALSE;
   }
 
// GET SCALE FACTORS FOR RESIZE
   $scaleX = $height / $imageY;
   $scaleY = $width / $imageX;
 
// THE WIDTH IS TOO GREAT - MUST RESIZE
   if ($scaleY < $scaleX)
   {
      $tnailX = $width;
      $tnailY = (int) ($scaleY * $imageY);
   }
// THE HEIGHT IS TOO GREAT - MUST RESIZE
   else
   {
      $tnailY = $height;
      $tnailX = (int) ($scaleX * $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 ;
}
 
?>
 
UPLOAD SCRIPT - upload_final.php
<?php // RAY_upload.php UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE
$debug = 1;
// PARAMETERS
	// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
		$folder = ""; // $_SERVER['DOCUMENT_ROOT']; // Root folder
 
	//On some sites I called the folder to upload (picfolder, filefolder, upfolder)
	// This would make them all the same.
		if ($_REQUEST['picfolder']) { $upfolder = $_REQUEST['picfolder']; }
		if ($_REQUEST['filefolder']) { $upfolder = $_REQUEST['filefolder']; }
		if ($_REQUEST['upfolder']) { $upfolder = $_REQUEST['upfolder']; }
		
	    $abpath = "$folder/";
	    if ($upfolder) $abpath .= "$upfolder"; //Absolute path to where images are uploaded. 
if ($debug) echo "L20 $abpath<br>\n";
		
	// Full Image Sizes
		$max_width=600;
		$max_height=800;
		$quality = 65;
 
	// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
		$max_file_size = 5000000; // A BIT MORE THAN 4MB
 
include ("uploadfunctions.php");
 
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'photos';
 
// 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>"
);
 
// START PHOTOS
if ($action == "photos") {
 
	if (isset($_POST['submitted']) ) 
{
if ($debug) echo "L45 $abpath<br>\n";
// 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(preg_replace("/[^a-z0-9.]/", "_", strtolower(current(explode( '.', basename($_FILES['userfile']['name'] ))))));	
	$my_new = getcwd() . '/' . $abpath . '/' . $f_name .'.'. $f_type;
	$my_file= $abpath . '/' . $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, $quality);
		}
	}
 
	echo "<p><a href=\"$my_file\">See the file</a></p>\n";
 
 
	die('Done');
}
 
 
	?>
	<h2>Upload Photos</h2>
 
	<!-- ENCTYPE -->
	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="action" value="photos" />
	<input type="hidden" name="p" value="1" />
	<input type="hidden" name="upfolder" value="photos" />
	<!-- 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="submitted" 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();
} 
?>

Open in new window

Top Expert 2008

Commented:
Change line 131:

 if ($imageblob = create_right_size_image($my_new))

...into this:

 if ($imageblob = create_right_size_image($my_new,$max_width,$max_height))

$max_width and $max_height are set in lines 111 and 112 in the snippet you posted. You can move this to a configuration file or grab it from the $_POST array, as you mentioned here: http:#a24882480

Author

Commented:
What about lines 39 & 40 in uploadfunctions.php. I changed it to:
function create_right_size_image($image, $max_width, $max_height)
//function create_right_size_image($image, $width=600, $height=800)

Error Msg:
Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/tylerweb/public_html/test/uploadfunctions.php on line 78

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/tylerweb/public_html/test/uploadfunctions.php on line 79
Top Expert 2008
Commented:
>> What about lines 39 & 40 in uploadfunctions.php. I changed it to:
>> function create_right_size_image($image, $max_width, $max_height)

That is wrong. The parameters are named $width and $height within the function. Leave it as it was:

function create_right_size_image($image, $width=600, $height=800)

Author

Commented:
OK, that works. Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial