Sponsored Links :

  • One of the more surprising things you can learn about PHP is that it’s actually very useful when it comes to manipulating images of varying filetypes and formats. And a good thing too, since a lot of the internet is made up of pictures!

    The functionality of PHP in terms of image manipulation ranges from very simple resizing of images through to more complex effects and functions using image libraries such as ImageMagick

    In this tutorial, I’ll take you through some of the more common uses for PHP when manipulating images, and then introduce you to some of the cooler aspects of this powerful little tool, which could help you to really add a bit of jazz and sparkle to your website!

    Let’s start with something simple. We’ll take a particular image, how about, let’s say, an image of a cute puppy and then run some functions on it to determine a few facts about it.

    getimagesize()

    We’ll start here by determining the image type (is it a jpeg, gif, png?), dimensions (height and width) and a few other things by using the getimagesize() function. Note that for this example, the image we’re using - puppy.jpg - must be in the same directory as the PHP script we’re calling this function from

    $info = getimagesize("puppy.jpg");
    print_r ($info);

    The function returns an array containing all of the relevant information, so the above code will produce

    Array (
      [0] => 491 //width
      [1] => 367 //height
      [2] => 2 //this number is a constant representing the image type
      [3] => width="491" height="367"
      [bits] => 8  //number of bits-per-pixel in the image
      [channels] => 3 // 3 = RGB, 4 = CMYK
      [mime] => image/jpeg //determines the filetype
    )

    From this we can tell the image is 491 by 367 pixels in size, with an 8-bit colour depth, and 3 colour channels. We also have the filetype, stored as the “mime” value of the array - “image/jpeg”.

    Another way we can retrieve the type of image used is to make use of PHP’s image_type_to_extension() function which will take, as its argument, the value of the array in index “2″ - in this case a value of 2, which represents the filetype of the image. So, for this value we get

    echo image_type_to_extension(2);

    which outputs

    .jpeg

    So, now we have this information, what else can we do with the file? We could try resizing the image, and saving a new copy of it. But first, let’s just try reading in the file data and see what happens

    header("Content-Type: image/jpeg");
    $image = @imagecreatefromjpeg("puppy.jpg");
    imagejpeg($image);
    imagedestroy($image);
    And behold, a picture of a cute puppy!

    And behold, a picture of a cute puppy!

    • Line 1 : This header value tells the browser to interpret the following data as Jpeg image data
    • Line 2 : Read the image data from the file, puppy.jpg using imagecreatefromjpeg(). The @ symbol simply supresses any errors that might occur. This creates a GD Resource $image, which can then be manipulated as required, or sent as output to the browser. Function like this one are part of PHP’s GD2 Library of image manipulation functions. Each function works on, or loads/saves an object representing image data called a GD Resource.
    • Line 3 : imagejpeg() is the function that outputs the image data to the browser
    • Line 4 : After we have output the image data, destroy the image resource with imagedestroy()

    So that’s how we read in and print out simple jpeg data. Similar functions also exist for PNG and GIF filetypes - namely imagecreatefromgif(), imagegif() and imagecreatefrompng(), imagepng()

    Resizing and Rotation

    What else can we do with the image once we’ve loaded it into memory with imagecreatefromjpeg()? Let’s try resizing the image. Here we will make use of the imagecreatetruecolor() function to create a blank GD resource to copy the resized image into, and the imagecopyresampled() function to perform the copying.

    The arguments for imagecopyresampled() are as follows

    bool imagecopyresampled  ( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )

    Which might need a little explanation: The first two are relatively straightforward, $dst_image is the GD resource to copy to, and $src_image is the GD resource to copy from. After these two arguments are 8 parameters that specify (x, y) co-ordinates on both the source and destination images, and width and height values for the source and destination images also.

    These points and widths are used to calculate which area of the source image is to be copied based on the top-left (x, y) co-ordinates and the source width and height, and the new width and height of the destination image, as well as the top-left co-ordinate values for the new image to start at

    When we call imagecreatetruecolor() we must also specify a width and height for this destination image.

    header("Content-Type: image/jpeg");
    $image = @imagecreatefromjpeg("puppy.jpg");
    $size = getimagesize("puppy.jpg");
    $percent = 150/100;
    $image_dest = @imagecreatetruecolor($size[0]*$percent, $size[1]*$percent);
    imagecopyresampled($image_dest, $image, 0, 0, 0, 0, $size[0]*$percent, $size[1]*$percent, $size[0], $size[1]);
    imagejpeg($image_dest);

    This will output an image 150% the width and height of the original. You can control the size of the image by changing the value of $percent. With some experimentation you can also try changing the ratio of the width and height to distort the image, and change the values within imagecopyresampled() to change the portion of the image that is resized.

    Why not try image rotation by replacing the imagejpeg($image_dest); function call to the following

    // 0x000000 is the background colour to use for the blank
    // space left after the rotation calculation
    $rotate = imagerotate($image_dest, 45.0, 0x000000);
    imagejpeg($rotate);
    Cute puppy has been rotated 45 degrees. Poor thing

    Cute puppy has been rotated 45 degrees. Poor thing

    Saving the Image To Disk

    Once you’ve manipulated the image enough, you may then want to save it to disk. A common usage for such a function is the use of generated thumbnail images for image upload sites. The idea being that a user would upload an image to a forum, or an image hosting site, and they would be given the option of either linking to the full-size image, or to a small thumbnail of the image.

    Such functionality is easy to achieve with the GD2 library, we simply modiy to the code from earlier by adding a new parameter to imagejpeg. This simply saves the GD resource to a file on the disk, as specified by the name given.

    $image = @imagecreatefromjpeg("puppy.jpg");
    $size = getimagesize("puppy.jpg");
    // let's save a 33% thumbnail
    $percent = 33/100;
    $image_dest = @imagecreatetruecolor($size[0]*$percent, $size[1]*$percent);
    imagecopyresampled($image_dest, $image, 0, 0, 0, 0, $size[0]*$percent, $size[1]*$percent, $size[0], $size[1]);
    // modify this final line to add an extra parameter to imagejpeg
    imagejpeg($image_dest, "puppy_thumb.jpg");
    New, smaller thumbnail puppy

    New, smaller thumbnail puppy

    This then results in a new file on the disk, smaller in size and dimensions than the original called “puppy_thumb.jpg”. The original file is not overwritten or modified during this action. We have also removed the header() function call from the first line, since we will no longer be writing the image data to the browser window.

One Response

WP_Cloudy

Leave a Comment

Want to ask a question about anything in this tutorial? Have you spotted an inaccuracy, or noticed areas for improvement? Fancy just having a chat? Leave your comments below...

Recommended Reading from Amazon.com

Previous Tutorial
Reporting and handling errors in PHP


Next tutorial
Working with dates and times in PHP