PHP Articles
Basic & Beginners
Advanced
Database
XML, Webservices
Design Patterns
Ajax
All Articles
Main Menu
Home
About PHP Hacks
Links
Contact Us
Search


Creating images using GD PDF Print E-mail
Monday, 17 July 2006
PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

We will look at an example of creating a thumbnail from an image in PHP. Furthermore you will learn to batch process a whole folder of images and create their thumbnails.

Before going any further let’s ensure our server is capable of creating the images.

To create images with PHP you need to have the gd image library installed and activated in your PHP.

To make sure if gd is installed on your machine, simply check your php info. Create a file that contains:

<?phpinfo()?>

and save it as "test.php" on your server. When you open it in a browser you see a colorful table showing all the schematics of your PHP install. In it you have to find something like this: Example of a php with gd installed

If you know for sure that there is gd on the machine but PHP does not recognize it, it may still be commented in the php.ini.

Scan your machine for the php.ini and edit it in a text editor. You will find loads of extensions:

;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd.dll
;extension=php_gettext.dll
;extension=php_hyperwave.dl

Simply remove the ";" in front of the php_gd and restart your server.

;extension=php_fdf.dll
;extension=php_filepro.dll
extension=php_gd.dll
;extension=php_gettext.dll
;extension=php_hyperwave.dl

Your server is running PHP, gd support is enabled, let's start thinking about the code.

To generate thumbnails we do the following:

•    Scan a folder for JPG and PNG files (gd does not support GIF anymore, because the packing algorithm in GIF is copyrighted).
•    Take each of these images, and load it.
•    Resize the image.
•    Save the image as a thumbnail.

The resizing idea is the following:

•    We assume the thumbnail should be 100 pixels, either wide or high.
•    We load the original image, and check its dimensions.
•    If the picture is higher than wide, we set the height of the thumb to 100 pixels.
•    The width of the thumbnail is the original width multiplied with 100 pixels divided by its height.
•    Thumbnail height = original width * (100 / original height)
•    This way we preserve the original aspect ratio.
•    If the original picture is wider than high, we do the same to the height of the thumbnail.
•    If they are the same, we simply create a 100x100 pixels image.

PHP has a whole lot of functions to help us with generating graphics with gd.

The ones we need to use here are:

•    imageCreateFromJPEG() to create a copy to work on of a .jpg image.
•    imageCreateFromPNG() to create a copy to work on of a .png image.
•    imageSX() to get the width of the original image.
•    imageSY() to get the height of the original image.
•    ImageCreateTrueColor() to create a new truecolour image object.
•    imageCopyResampled() to resample the image.

GD supports truecolour images from version 2.0 onwards, older versions of GD will create JPGs and PNGs with 256 colors and need other functions.
 
•    imageJPEG() to create a new JPEG image.
•    imagePNG() to create a new PNG image.
•    imagedestroy() to delete the old image objects in the memory.

Furthermore I created some functions I keep using:

•    directory() reads a folder and returns all the files that apply to a certain filter.
•    ditchtn() clears the resulting array from all files starting with a filter you define, like tn_".
•    createthumb() creates a thumbnail and saves it to the server.

The main thumbnail generation function

createthumb() is the main thumbnail generation function, so let's take a closer look:

function createthumb($name,$filename,$new_w,$new_h){
    $system=explode('.',$name);
    if (preg_match('/jpg|jpeg/',$system[1])){
        $src_img=imagecreatefromjpeg($name);
    }
    if (preg_match('/png/',$system[1])){
        $src_img=imagecreatefrompng($name);
    }

createthumb() is called with the following parameters: The name of the original image (if needed with folder name), the name of the thumbnail picture, and the dimensions.

These lines get the information, if gd is at least version 2.0 and check if the original image is a JPEG or PNG.

Accordingly, a new image object is created called src_image.
    
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
    $thumb_w=$new_w;
    $thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
    $thumb_w=$old_x*($new_w/$old_y);
    $thumb_h=$new_h;
}
if ($old_x == $old_y) {
    $thumb_w=$new_w;
    $thumb_h=$new_h;
}

These lines get the dimensions of the original image by using imageSX() and imageSY(), and calculate the dimensions of the thumbnail accordingly, keeping the correct aspect ratio. The desired dimensions are stored in thumb_w and thumb_h.

    $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

These lines create the image as a true color version using ImageCreateTrueColor() and resize and copy the original image into the new thumbnail image, on the top left position.

    
if (preg_match("/png/",$system[1]))
{
    imagepng($dst_img,$filename);
} else {
    imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}

These lines check the file system extension of the original image and create the thumbnail accordingly. The thumbnail gets saved onto the server (by adding a filename to imagejpeg() or imagepng() function) and the two image objects get destroyed to free the memory.

Let's say you have an original picture called apple.jpg in a folder named pics and you want to generate the thumbnail in the folder thumbs as tn_apple.jpg 100x100 pixels big.

You can do this by calling this function with the following parameters:

createthumb('pics/apple.jpg','thumbs/tn_apple.jpg',100,100);

To batch process all the pictures in the folder pics and generate their thumbnails in the folder thumbs you would need to do the following:

$pics=directory('pics','jpg,JPG,JPEG,jpeg,png,PNG');
$pics=ditchtn($pics,'tn_');
if ($pics[0]!='')
{
    foreach ($pics as $p)
    {
        createthumb('pics/'.$p,'thumbs/tn_'.$p,100,100);
    }
}

Grab all the pictures from the pics folder via directory() and a filter for images.

Then delete all the thumbnails by using ditchtn() and make sure that the resulting array is not empty.

The second parameter in ditchtn() must match the name you gave your thumbnails, this is done to prevent thumbnails being generated from thumbnails.

Next, loop over all images and generate the thumbnail with the desired dimensions and names.

Generating thumbnails with PHP is pretty handy and saves you a lot of time pushing files onto your server via FTP. It also makes it easier to keep an image gallery up to date.

PHP with gd can be very slow at times though, especially when the machine is not fast enough and the resample() function is used. Some servers might give you an error related to maximum time for script execution. You can change this in your php.ini:

max_execution_time = 320 ; Maximum execution time of each script, in seconds

Now, try to generate some thumbnails on your own server by playing with the thumbnail generator.

Comments
Add NewSearchRSS
Vishal - Mr IP:203.145.159.40 | 2007-03-18 18:42:14
Awesome tutorial.
nossidge.com - Hmm... IP:212.159.78.251 | 2007-05-26 15:24:39
Seems to be stolen from http://icant.co.uk/articles/phpthumbnails/

The original article actually worked, though. The code for ditchtn() and directory() was in the download that was at the bottom of the original article. Their absence here makes this tutorial worthless, as the batch process will not work without those functions.
Only registered users can write comments!
 
< Prev   Next >

Syndicate


Login Form





Lost Password?
No account yet? Register