Uploading and resizing an image - tutorial

Tutorials on PHP, databases and other aspects of web development. Before posting a question, check in here to see whether there's a tutorial that covers your problem.

Moderator: General Moderators

Post Reply
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Uploading and resizing an image - tutorial

Post by onion2k »

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: Select all

<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.

Code: Select all

$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.

Code: Select all

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.

Code: Select all

$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.

Code: Select all

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().

Code: Select all

$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.

Code: Select all

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.

Code: Select all

imagejpeg($thumb, "images/thumbnail.jpg", 80);
The thumbnail generation script in full:

Code: Select all

<?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);

?>
User avatar
funkyfela
Forum Newbie
Posts: 4
Joined: Sun Jul 20, 2008 6:03 pm
Contact:

Re: Uploading and resizing an image - tutorial

Post by funkyfela »

Hi.
I followed your tutorial but the code is not working for me. Gives a lot of error.
Or is it because of my php version? maybe you should try your codes on php5 and higher to see the result.

Anyway. Thanks for the tut.

Hope to get a working version
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Uploading and resizing an image - tutorial

Post by John Cartwright »

This is the 2nd thread today that was resurrected from a 5 year old grave. I'm not even sure PHP5 was out 5 years ago...

But really, please leave dead threads to die peacefully.
layooo
Forum Newbie
Posts: 0
Joined: Mon Jun 28, 2010 1:07 pm

Re: Uploading and resizing an image - tutorial

Post by layooo »

nice,I learned it from php100.
sayed85
Forum Newbie
Posts: 0
Joined: Tue Jun 29, 2010 9:23 am

Re: Uploading and resizing an image - tutorial

Post by sayed85 »

Thanks for the post. It helps me a lot.
almedajohnson
Forum Newbie
Posts: 7
Joined: Sun Sep 19, 2010 11:21 pm

Re: Uploading and resizing an image - tutorial

Post by almedajohnson »

I think it would be helpful to everyone. Though uploading an image is not so difficult but resizing an image is very daunting task and need special coding as we have to maintain the quality.
clobydenz12
Forum Newbie
Posts: 1
Joined: Wed Jan 09, 2013 10:41 am
Location: Orlando,Florida

Re: Uploading and resizing an image - tutorial

Post by clobydenz12 »

Pretty useful tutorial. Thanks a lot! I am working on my blog presently, I hope this tutorial will work for me.
Delgado2009
Forum Newbie
Posts: 5
Joined: Thu Oct 27, 2011 3:46 pm

Re: Uploading and resizing an image - tutorial

Post by Delgado2009 »

clobydenz12 wrote:Pretty useful tutorial. Thanks a lot! I am working on my blog presently, I hope this tutorial will work for me.
If you are using WordPress, you should try the new function WP Image Editor instead of this tutorial.
essenza
Forum Newbie
Posts: 2
Joined: Tue Jun 04, 2013 4:04 pm

Re: Uploading and resizing an image - tutorial

Post by essenza »

very nice, thanks for sharing.

If you are posting on the same page action attribute can be omitted.


__________
Free hosting
Post Reply