Hi

I am trying to upload multiple images add them to a database and resize the images.

The page I have will upload the image and add it to the database, but the image will not resize.

I am getting the following error

Warning: imagecopyresampled() expects parameter 2 to be resource, string given in C:\wamp\www\haldon\admin\upload.php on line 90

The code for the page is

<?php
    error_reporting( E_ALL );
	include("config.inc.php");
    include('../includes/connect_inc.php');

// initialization
$result_final = "";
$counter = 0;

// List of our known photo types
$known_photo_types = array( 
					'image/pjpeg' => 'jpg',
					'image/jpeg' => 'jpg',
					'image/gif' => 'gif',
					'image/bmp' => 'bmp',
					'image/x-png' => 'png'
				);

// GD Function List
$gd_function_suffix = array( 
					'image/pjpeg' => 'JPEG',
					'image/jpeg' => 'JPEG',
					'image/gif' => 'GIF',
					'image/bmp' => 'WBMP',
					'image/x-png' => 'PNG'
				);

// Fetch the photo array sent by add-photos.php
$photos_uploaded = $_FILES['photo_filename'];

// Fetch the photo caption array
$photo_caption = $_POST['photo_caption'];

while( $counter <= count($photos_uploaded) )
{
	if($photos_uploaded['size'][$counter] > 0)
	{
		if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types))
		{
			$result_final .= "File ".($counter+1)." is not a photo<br />";
		}
		else
		{
			mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" );
			$new_id = mysql_insert_id();
			$filetype = $photos_uploaded['type'][$counter];
			$extention = $known_photo_types[$filetype];
			$filename = $new_id.".".$extention;

			mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" );
            //resize photos to maximum height or width
            //define parameters - maximum height & width for new images
            $image_max_width=599;
            $image_max_height=599;
            $max_dimension=800;
            // Grab the width and height of the image.
            list($width,$height) = getimagesize($photos_uploaded['tmp_name'][$counter]);
            // If the max width input is greater than max height we base the new image off of that, otherwise we
            // use the max height input.
            // We get the other dimension by multiplying the quotient of the new width or height divided by
            // the old width or height.
            echo 'Line: ' . __LINE__ . '$width = ' . $width . '<br/>';
            echo 'Line: ' . __LINE__ . '$width = ' . $height . '<br/>';
            echo 'Line: ' . __LINE__ . '$image_max_width = ' . $image_max_width . '<br/>';
            echo 'Line: ' . __LINE__ . '$image_max_height = ' . $image_max_height . '<br/>';
            if($image_max_width > $image_max_height){
            if($image_max_width > $max_dimension){
            $newwidth = $max_dimension;
            } else {
            $newwidth = $image_max_width;
            echo 'Line: ' . __LINE__ . '$newwidth = ' . $newwidth . '<br/>';
            }
            $newheight = ($newwidth / $width) * $height;
            } else {
            if($image_max_height > $max_dimension){
            $newheight = $max_dimension;
            } else {
            $newheight = $image_max_height;
            }
            $newwidth = ($newheight / $height) * $width;
            }
            echo 'Line: ' . __LINE__ . '$newwidth = ' . $newwidth . '<br/>';
            echo 'Line: ' . __LINE__ . '$newheight = ' . $newheight . '<br/>';
            // Create temporary image file.
            $tmp = imagecreatetruecolor($newwidth,$newheight);
            // Copy the image to one with the new width and height.
            echo 'Line: ' . __LINE__ . 'photoname = ' . $photos_uploaded['tmp_name'][$counter] . '<br/>';
            echo 'Line: ' . __LINE__ . '$tmp = ' . $tmp . '<br/>';
            $photoname=$photos_uploaded['tmp_name'][$counter];
            imagecopyresampled($tmp,$photoname,0,0,0,0,$newwidth,$newheight,$width,$height);
            //end of resizing
			// Store the orignal file
			copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename);

			// Let's get the Thumbnail size
			$size = GetImageSize( $images_dir."/".$filename );
			if($size[0] > $size[1])
			{
				$thumbnail_width = 100;
				$thumbnail_height = (int)(100 * $size[1] / $size[0]);
			}
			else
			{
				$thumbnail_width = (int)(100 * $size[0] / $size[1]);
				$thumbnail_height = 100;
			}

			// Build Thumbnail with GD 1.x.x, you can use the other described methods too
			$function_suffix = $gd_function_suffix[$filetype];
			$function_to_read = "ImageCreateFrom".$function_suffix;
			$function_to_write = "Image".$function_suffix;

			// Read the source file
			$source_handle = $function_to_read ( $images_dir."/".$filename ); 

			if($source_handle)
			{
				// Let's create an blank image for the thumbnail
			     	$destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height );

				// Now we resize it
		      	ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] );
			}

			// Let's save the thumbnail
			$function_to_write( $destination_handle, $images_dir."/tb_".$filename );
			ImageDestroy($destination_handle );
			//

			$result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />";
		}
	}
$counter++;
}
//header('Location: add-photos.php');
// Print Result
echo <<<__HTML_END

<html>
<head>
	<title>Photos uploaded</title>
</head>
<body>
	$result_final
</body>
</html>

__HTML_END;
?>

I understand that there may be a better way of doing this, any help you guys can provide will be much appreciated.

    Hi

    Thanks for your reply, I have added in the following line

    $image = imagecreatefromjpeg($images_dir."/".$filename);
    

    but get the following error:

    Warning: imagecreatefromjpeg(../photos/71.jpg) [function.imagecreatefromjpeg]: failed to open stream: No such file or directory in C:\wamp\www\haldon\admin\upload.php on line 90

    I feel that I am getting somewhere, but this is the first time I have attaempted anything like this.

      That means the file doesn't exist where you think it does. Is the $images_dir in the same directory as the PHP script?

        The images are stored in a different location to the php script (../photos/) and this has been referenced.

        I have just tried moving the entire block of code for the resizing to after the line

        copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename)
        

        There were no syntax errors, but the resizing did not take place.

          Were there any errors shown? Try echoing out variables at key parts of your code to see if what you expect is happening where you expect. Just saying that the resizing didn't work isn't really much help in debugging this.

            Yeah, sorry about that
            I have echodes some of the variables and moved the code to below the line

            copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename)

            The whole code now reads

            <?php
                error_reporting( E_ALL );
            	include("config.inc.php");
                include('../includes/connect_inc.php');
            
            // initialization
            $result_final = "";
            $counter = 0;
            
            // List of our known photo types
            $known_photo_types = array( 
            					'image/pjpeg' => 'jpg',
            					'image/jpeg' => 'jpg',
            					'image/gif' => 'gif',
            					'image/bmp' => 'bmp',
            					'image/x-png' => 'png'
            				);
            
            // GD Function List
            $gd_function_suffix = array( 
            					'image/pjpeg' => 'JPEG',
            					'image/jpeg' => 'JPEG',
            					'image/gif' => 'GIF',
            					'image/bmp' => 'WBMP',
            					'image/x-png' => 'PNG'
            				);
            
            // Fetch the photo array sent by add-photos.php
            $photos_uploaded = $_FILES['photo_filename'];
            
            // Fetch the photo caption array
            $photo_caption = $_POST['photo_caption'];
            
            while( $counter <= count($photos_uploaded) )
            {
            	if($photos_uploaded['size'][$counter] > 0)
            	{
            		if(!array_key_exists($photos_uploaded['type'][$counter], $known_photo_types))
            		{
            			$result_final .= "File ".($counter+1)." is not a photo<br />";
            		}
            		else
            		{
            			mysql_query( "INSERT INTO gallery_photos(`photo_filename`, `photo_caption`, `photo_category`) VALUES('0', '".addslashes($photo_caption[$counter])."', '".addslashes($_POST['category'])."')" );
            			$new_id = mysql_insert_id();
            			$filetype = $photos_uploaded['type'][$counter];
            			$extention = $known_photo_types[$filetype];
            			$filename = $new_id.".".$extention;
            
            			mysql_query( "UPDATE gallery_photos SET photo_filename='".addslashes($filename)."' WHERE photo_id='".addslashes($new_id)."'" );
            
            			// Store the orignal file
            			copy($photos_uploaded['tmp_name'][$counter], $images_dir."/".$filename);
                         //resize photos to maximum height or width
                        //define parameters - maximum height & width for new images
                        $image_max_width=599;
                        $image_max_height=599;
                        $max_dimension=800;
                        // Grab the width and height of the image.
                        list($width,$height) = getimagesize($photos_uploaded['tmp_name'][$counter]);
                        // If the max width input is greater than max height we base the new image off of that, otherwise we
                        // use the max height input.
                        // We get the other dimension by multiplying the quotient of the new width or height divided by
                        // the old width or height.
                        echo 'Line: ' . __LINE__ . '$width = ' . $width . '<br/>';
                        echo 'Line: ' . __LINE__ . '$width = ' . $height . '<br/>';
                        echo 'Line: ' . __LINE__ . '$image_max_width = ' . $image_max_width . '<br/>';
                        echo 'Line: ' . __LINE__ . '$image_max_height = ' . $image_max_height . '<br/>';
                        if($image_max_width > $image_max_height){
                        if($image_max_width > $max_dimension){
                        $newwidth = $max_dimension;
                        } else {
                        $newwidth = $image_max_width;
                        echo 'Line: ' . __LINE__ . '$newwidth = ' . $newwidth . '<br/>';
                        }
                        $newheight = ($newwidth / $width) * $height;
                        } else {
                        if($image_max_height > $max_dimension){
                        $newheight = $max_dimension;
                        } else {
                        $newheight = $image_max_height;
                        }
                        $newwidth = ($newheight / $height) * $width;
                        }
                        echo 'Line: ' . __LINE__ . '$newwidth = ' . $newwidth . '<br/>';
                        echo 'Line: ' . __LINE__ . '$newheight = ' . $newheight . '<br/>';
                        // Create temporary image file.
                        $tmp = imagecreatetruecolor($newwidth,$newheight);
                        // Copy the image to one with the new width and height.
                        echo 'Line: ' . __LINE__ . '$filename = ' . $filename . '<br/>';
                        echo 'Line: ' . __LINE__ . 'photoname = ' . $photos_uploaded['tmp_name'][$counter] . '<br/>';
                        echo 'Line: ' . __LINE__ . '$tmp = ' . $tmp . '<br/>';
                        $image = imagecreatefromjpeg($images_dir."/".$filename);
                        echo 'Line: ' . __LINE__ . '$image = ' . $image . '<br/>';
                        imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
                        //end of resizing
            			// Let's get the Thumbnail size
            			$size = GetImageSize( $images_dir."/".$filename );
            			if($size[0] > $size[1])
            			{
            				$thumbnail_width = 100;
            				$thumbnail_height = (int)(100 * $size[1] / $size[0]);
            			}
            			else
            			{
            				$thumbnail_width = (int)(100 * $size[0] / $size[1]);
            				$thumbnail_height = 100;
            			}
            
            			// Build Thumbnail with GD 1.x.x, you can use the other described methods too
            			$function_suffix = $gd_function_suffix[$filetype];
            			$function_to_read = "ImageCreateFrom".$function_suffix;
            			$function_to_write = "Image".$function_suffix;
            
            			// Read the source file
            			$source_handle = $function_to_read ( $images_dir."/".$filename ); 
            
            			if($source_handle)
            			{
            				// Let's create an blank image for the thumbnail
            			     	$destination_handle = ImageCreate ( $thumbnail_width, $thumbnail_height );
            
            				// Now we resize it
            		      	ImageCopyResized( $destination_handle, $source_handle, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $size[0], $size[1] );
            			}
            
            			// Let's save the thumbnail
            			$function_to_write( $destination_handle, $images_dir."/tb_".$filename );
            			ImageDestroy($destination_handle );
            			//
            
            			$result_final .= "<img src='".$images_dir. "/tb_".$filename."' /> File ".($counter+1)." Added<br />";
            		}
            	}
            $counter++;
            }
            //header('Location: add-photos.php');
            // Print Result
            echo <<<__HTML_END
            
            <html>
            <head>
            	<title>Photos uploaded</title>
            </head>
            <body>
            	$result_final
            </body>
            </html>
            
            __HTML_END;
            ?>
            

            The variables that output are:
            Line: 65$width = 1600
            Line: 66$width = 1200
            Line: 67$image_max_width = 599
            Line: 68$image_max_height = 599
            Line: 85$newwidth = 798.66666666667
            Line: 86$newheight = 599
            Line: 90$filename = 75.jpg
            Line: 91photoname = C:\wamp\tmp\php286C.tmp
            Line: 92$tmp = Resource id #10
            Line: 94$image = Resource id #12

            I appreciate all your help.

              What about $images_dir? Have you tried using an absolute path instead of a relative path? IE instead of doing ../folder starting at the root (which will be dependent on your environment) could for example be: C:\inetpub\www\folder (windows, iis) /usr/local/www/folder (*nix)

                You don't actually seem to be saving $tmp once you've copied your resampled image into it. By the sounds of it, it's working, but because you're not saving the image anywhere, PHP is discarding it. The previous link I sent you to the PHP Manual page for imagecopyresampled() shows you how to do this.

                  Write a Reply...