Resizing Images on upload,

Hi

I have a script that uploads images to a server and adds the details to a database, these parts work ok, I am also trying to resizew the images to a maximum width or height whilst keeping their ratio the same, this part isn’t working
The code I am using 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)."'" );

				// 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( $images_dir."/".$filename);
                // 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__ . '$images_dir = ' . $images_dir . '<br/>';
                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)or die('Cannot Initialize new GD image stream');
                // 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)or die();
                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 values of the variables that I have echoed are:

Line: 65$images_dir = ../photos Line: 66$width = 1600 Line: 67$width = 1200 Line: 68$image_max_width = 599 Line: 69$image_max_height = 599 Line: 86$newwidth = 798.66666666667 Line: 87$newheight = 599 Line: 91$filename = 86.jpg Line: 92photoname = C:\wamp\tmp\php119E.tmp Line: 93$tmp = Resource id #10 Line: 95$image = Resource id #12

??? So, what is the error you are getting? Or, what is wrong? You showed some code and some sort of output values, but, did not tell us what was wrong or what error you are getting… We can look at the code, but, can not help unless we know what we are looking for…

I am not getting any syntax errors, the variables that are being output are for debugging purposes, and it looks like there is a problem with the following variables:

Line: 93$tmp = Resource id #10 Line: 95$image = Resource id #12

affected by the following two lines

$tmp = imagecreatetruecolor($newwidth,$newheight)or die('Cannot Initialize new GD image stream');
$image = imagecreatefromjpeg($images_dir.'/'.$filename)or die();

But I adon’t know why.

About those lines you indicated:
Line: 93$tmp = Resource id #10
Line: 95$image = Resource id #12

Silly, that is correct! You can NOT PRINT a picture to the browser! So, PHP just points to a resource ID instead! All normal there… I suspect your resize logic is incorrect. I copied it into my editor and could not see a problem.

One thing I did notice is that you are calling the “GD” library in some lines and the PHP image functions in others… Why are you doing this? Normally, you use one or the other. If you do not know the difference, then that is your issue and we can help you. If you have a certain reason to use all that code to create a thumbnail, perhaps I am not seeing something.

Also, why do you do an INSERT and then an UPDATE right after that? You should only be doing one INSERT. It just waste time to retrieve the data you just wrote and UPDATE it back. Triple the database calls for a simple INSERT.

Lastly, if you are displaying thumbnails on a webpage, usually you want them the same width so that you set the number of images across the page. Then, if they are portrait photos, they are all the same width, but, some can be taller than others. (Shows nice this way!) Some thumbnail displays are set to be a set width AND a set height. Which did you want? Here is the general PHP image function calls to resize a picture to the 599-pixel width max keeping the proportions of the original… (my code, not yours, you will have to fix yours!)
Hope this helps…
[php]

<?PHP // $filename is the photo to resize... $image = imagecreatefromjpeg($filename); // Resize to 599 width... $imagex = imagesx($image); $imagey = imagesy($image); $ratio = 599 / $imagex; $height = $imagey * $ratio; $new_image = imagecreatetruecolor(599, $height); imagecopyresampled($new_image, $image, 0, 0, 0, 0, 599, $height, $imagex, $imagey); // Save the new thumbnail image... $newfilename="somefolder/somenametosave.jpg"; imagejpeg($new_image,$newfilename,75); [/php] That is about all you need to resize to a set width. Much easier. (I set the JPEG compression to 75...) Perhaps that will help you sort this out... (Oh, no GD calls, just image functions... Much faster!)

Hi

Thanks for your reply. It is very helpful.

In all honesty the page is a merger from two tutorials, and I have tried to make them work together.

I do not need it to create the thumbnails, I will try and remove that part of the page.

The images are displayed on the pages using a max-width in CSS, I want them to find which is the largest, width or height and set that to 599 and then change the other side to the relevant size based on the ratio.

Well, you can do this the same way for CSS, just alter the CSS using your PHP code.
Your PHP code can be used inside each picture display to alter whatever you need in the CSS code.

I prefer the thumbnail version as it is easy code as in my example and once completed, the thumbnails are done and little code needs to be changed in the display of them… Well, good luck with your project!

Hi ErnieAlex

I think I explained myself wrong, I am going to remove the thumbnail part of the script thatis there at the moment as that serves no purpose.

The pictures are displayed on the site using the max-width css property. However when the user clicks on the image it loads in a lightbox and it is here that the resized image will be displayed.

If you want to see the page that the images are displayed check out

www.haldonguesthouse.co.uk/accommodation

Thanks

Sponsor our Newsletter | Privacy Policy | Terms of Service