Posts Tagged ‘image manipulation’

Using the PHP GD Graphic Library

Thursday, October 30th, 2008

Today, I will walk you through the process of using the GD Library.  This library is installed on most PHP servers, and works really well when you want to allow someone to upload an image of any size, and then resize it into a proper thumbnail.

First of lets create a simple form that allows us to upload our image file in a file called image.php

<h1>Upload Image</h1>
<p>
     Below will be a preview of our image once uploaded:
</p>
<img src="images/thumb.jpg" alt="Preview Will Be Shown Here" />
<form action="image.php" enctype="multipart/form-data" method="post">
    <label for="image">Image</label>
        <input id="image" name="image" type="file" />
        <input name="submit" type="submit" value="Upload!" />
</form>

Here we have setup that thumb.jpg will be shown. Of course we have not yet uploaded an image so nothing will show up here yet. We have set the action to be the same file, so it will just keep posting back the information to itself. Another important attribute of the form that we need to assign is the enctype. If this is not here, it will not send our image across properly.

We now need to do some fancy PHP when the above form is submitted. Add this above the form:

< ?php
if( isset($_POST['submit']) )
{
    // gets the variable needed from our type=file field with a name of image
    $image = $_FILES['image']['tmp_name'];

    // makes sure we have browsed to an image and not left it blank
    if( !empt y($image) )
    {
        // put the contents of the image into a php variable
        $src = imagecreatefromjpeg($image);

        // get the original images width and height
        list($width, $height) = getimagesize($image);

        // calculate the new width and height that we want our image to be
        // height is calculated to keep the same ratio with our new width
        $newwidth = 100;
        $newheight = ($height/$width)*$newwidth;

        // create a holder for our new image, and copy the original with new dimensions
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

        // lastly output the new image to our directory structure
        imagejpeg($tmp,'images/thumb.jpg',100);
    }
}
?>

One last thing to do is make sure your “images” directory is writable. Now open up your image.php file and try it out. It should now allow you to resize any image into a great looking thumbnail!

Download Tutorial Files

Tags: ,
Posted in Web Programming | 2 Comments »

 
connect with me!