FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Uploading and resizing an image





shinji_x19
One of the most common practises in PHP coding with GD is to create a thumbnail image of an uploaded file. In this tutorial we will examine an image upload form, look at PHP's file upload system, and use an uploaded image to create a small thumbnail image.

PHP's built in system for uploading files allows us to create an HTML form that uses the "file" element. This is a type of HTML input tag that tells a user's web browser to display a file selection dialogue, and to include any selected file with the data sent along with a form.

Code:
<form action="index.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="200000">";
<input type="file" name="imagefile">
<input type="submit" name="upload" value="Upload Image">
</form>

Note that this form includes two elements that normal web forms often don't. The first is the enctype attribute in the form tag. This tells the user's browser how to encode the file data before sending it. Without this attribute PHP will not know how to decode the file when it receives it. It's vital. The other element that is included is a hidden form element called MAX_FILE_SIZE. The value of this element tells PHP the maximum size of file to allow. In practise it's more sensible to limit the uploaded file size using your php.ini file.

When PHP receives the submitted form it takes the file, or files, that have been uploaded and places details of them in the $_FILES array. This array gives us plenty of information about the file that was uploaded: it's type, it's filename, and where PHP has temporarily stored it. Using the file type information that PHP puts in the Array array we can determine what sort of file the user has uploaded and open it using the correct PHP function. It might be tempting to use the file extension to determine the image type, .gif for example, but this can be dangerous. Some non-Windows computers do not use an extension, so you cannot be certain that an upload will have one either. All uploaded files have to include their MIME type.

Once we have determined the file type and opened the image file we can then delete the file from PHP's temporary storage. This isn't terribly important, but it's good practise to tidy up when we have the opportunity.

php:
$filename = $_FILES['imagefile']['name'];
$temporary_name = $_FILES['imagefile']['tmp_name'];
$mimetype = $_FILES['imagefile']['type'];
$filesize = $_FILES['imagefile']['size'];

switch($mimetype) {
case "image/jpg":
case "image/jpeg":
case "image/pjpeg": //IE's weird jpeg MIME type
$i = imagecreatefromjpeg($temporary_name);
break;
case "image/gif":
$i = imagecreatefromgif($temporary_name);
break;
case "image/png":
$i = imagecreatefrompng($temporary_name);
break;
}

unlink($temporary_name);

At this stage we should now have a GD resource that contains the uploaded image in the variable $i. If a copy of the original is required then it should be saved at this point.

php:
imagejpeg($i,"images/uploadedfile.jpg",80);

In this example the file has been saved as a jpg, but you might want to write some code to save the file in the same format it was uploaded in.

Now that we have the image as open as a GD resource we can go about the process of creating a resized thumbnail version of it. The key processes involved are creating a new image that is proportionally smaller, and then copying the original image data to it.

To create the smaller image we need to calculate the width and height based upon the dimensions of the original. In order to do this we need to know the maximum width and height that a thumbnail should be.

php:
$dest_x = 150;
$dest_y = 150;

Once we have established the maximum width and height we can then calculate the final width and height based on the relationship of the dimensions of the original compared to the desired size of the thumbnail.

php:
if (imagesx($i) > $dest_x or imagesy($i) > $dest_y) {
if (imagesx($i) >= imagesy($i)) {
$thumb_x = $dest_x;
$thumb_y = imagesy($i)*($dest_x/imagesx($i));
} else {
$thumb_x = imagesx($i)*($dest_y/imagesy($i));
$thumb_y = $dest_y;
}
} else {
$thumb_x = imagesx($i);
$thumb_y = imagesy($i);
}

The code first checks to see if either the width or height of the original are larger than the desired width or height. If either is then the code checks to see which dimension is greater; if the width is the larger dimension then the height is scaled proportionally to the width, and the width is set to the maximum size of the thumbnail. If the height is the larger dimension then the width is scaled while the height is set to the maximum possible size.

Now that the dimensions of the thumbnail are known we can create a new image based on them. There are two options for creating a new image with GD: imagecreate() and imagecreatetruecolor(). Imagecreate() generates a palette based 256 color image while imagecreatetruecolor() gives us a true color image capable of storing 16.8 million colors. Resizing to a 256 color image often looks dirty or washed out due to the nature of color replacement, so we'll use imagecreatetruecolor().

php:
$thumb = imagecreatetruecolor($thumb_x,$thumb_y);

Now that the thumbnail image is created we have to copy the image data onto it. The resizing process is done automatically by PHP's imagecopyresampled() function.

php:
imagecopyresampled($thumb, $i ,0, 0, 0, 0, $thumb_x, $thumb_y, imagesx($i), imagesy($i));

There is also a quicker option to resize the image. PHP's imagecopyresized() function is a lot faster, and less CPU intensive than imagecopyresampled(). However, it uses a basic 'Nearest Neighbour' algorithm so the results look blocky and poor quality.

$thumb now contains a smaller version of . At this stage it is sensible to save the thumbnail image so that we don't have to create it again.

php:
imagejpeg($thumb, "images/thumbnail.jpg", 80);


The thumbnail generation script in full:

php:
<?php

// Get the details of "imagefile"
$filename = $_FILES['imagefile']['name'];
$temporary_name = $_FILES['imagefile']['tmp_name'];
$mimetype = $_FILES['imagefile']['type'];
$filesize = $_FILES['imagefile']['size'];

//Open the image using the imagecreatefrom..() command based on the MIME type.
switch($mimetype) {
case "image/jpg":
case "image/jpeg":
$i = imagecreatefromjpeg($temporary_name);
break;
case "image/gif":
$i = imagecreatefromgif($temporary_name);
break;
case "image/png":
$i = imagecreatefrompng($temporary_name);
break;
}

//Delete the uploaded file
unlink($temporary_name);

//Save a copy of the original
imagejpeg($i,"images/uploadedfile.jpg",80);

//Specify the size of the thumbnail
$dest_x = 150;
$dest_y = 150;

//Is the original bigger than the thumbnail dimensions?
if (imagesx($i) > $dest_x or imagesy($i) > $dest_y) {
//Is the width of the original bigger than the height?
if (imagesx($i) >= imagesy($i)) {
$thumb_x = $dest_x;
$thumb_y = imagesy($i)*($dest_x/imagesx($i));
} else {
$thumb_x = imagesx($i)*($dest_y/imagesy($i));
$thumb_y = $dest_y;
}
} else {
//Using the original dimensions
$thumb_x = imagesx($i);
$thumb_y = imagesy($i);
}

//Generate a new image at the size of the thumbnail
$thumb = imagecreatetruecolor($thumb_x,$thumb_y);

//Copy the original image data to it using resampling
imagecopyresampled($thumb, $i ,0, 0, 0, 0, $thumb_x, $thumb_y, imagesx($i), imagesy($i));

//Save the thumbnail
imagejpeg($thumb, "images/thumbnail.jpg", 80);

?>
Animal
Moved to Tutorials forum
Related topics
PHP Image Upload (MySQL/Folder)
PHP Tutorials
Which is the best Mobile phone
pls suggest software to generate thumbnails etc...
PHP image uploads with progress bar AND resizing? [Resolved]
Post your Wallpapers
Automatic File Uploader Anyone?
I want to take a picture of my screen
Resize image in PNG Problem
upload image through PHP AND AJAX
Uploading an Image using PHP script - RESOLVED
Uploading an Image
How to use tags for search
www.imagegarage.net
Reply to topic    Frihost Forum Index -> Miscellaneous -> Tutorials

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.