Web Hosting Talk







View Full Version : Using GD to resize images and then upload.


MGHosted.net
10-30-2004, 07:05 PM
Hey guys,

I have a form, you browse for an image and it puts it into your temp files. It then resizes it, and now I need it to be reuploaded to my /thumbnails/ folder. I don't know how, ive tried everything.

This is my code:


// File and new size
$filename = $_FILES['upload']['tmp_name'];

// Content type
header('Content-type: image/jpeg');

// Get Image sizes.
list($width, $height) = getimagesize($filename);

// Load
$thumb = imagecreatetruecolor(200, 150);
$source = imagecreatefromjpeg($filename);

// Resize
$resized = imagecopyresized($thumb, $source, 0, 0, 0, 0, 200, 150, $width, $height);

// Output
$fileoutput = imagejpeg($thumb);


Any help is appreciated

Codefighter
11-01-2004, 03:42 AM
I'm not sure I completely understand your question, as it seems contradictng, but I'll give it a go.

First, you say "you browse for an image and it puts it into your temp files". The image doesn't make it into the temp folder on the users computer, but in the webservers temp folder when the user uploads the image file. This then confuses my on your point that you want to "re-upload" it to your server, when it actually will only be uploaded to your server once.

Second, the code you presented is designed to display the image to the end user, not to store it locally on your server. The key to this, is the imagejpeg method where you are giving it a single parameter. Note that for imagejpeg, there is a second optional parameter that indicates a filename on your server to store the image. Chances are all you want to do is to add the filename as the last paremeter to imagejpeg.

In any case, here is a sample form that will let the user select an image from their hard drive, then upload it to a server, and once on the server will resize it and save it to a second file with a tn_ prefix in the filename (for 'thumb nail').

Note however that your scripts will also need write permissions to the folder where the images are being stored (I put them in /images in this example).

<?php if( !isset( $_POST["ACT"] ) ) { ?>
<form method="post" action="em.php" enctype="multipart/form-data">
<input type=hidden name=ACT value=UPLOAD>
<input type="file" name=upload> <input type=submit>
</form>
<?php } else {

$Filename = $_FILES["upload"]["name"];
if( strlen( $Filename ) > 0 )
{
move_uploaded_file( $_FILES["upload"]["tmp_name"], "images/$Filename" );
list($width, $height) = getimagesize("images/$Filename");

// Load
$thumb = imagecreatetruecolor(200, 150);
$source = imagecreatefromjpeg("images/$Filename");
// Resize
$resized = imagecopyresized($thumb, $source, 0, 0, 0, 0, 200, 150, $width, $height);
// Output
imagejpeg($thumb, "images/tn_$Filename");
echo "Image and thumbnail stored.";
}
}
?>