Cyber Monday Sale! 50% off themes, plugins, graphics, audio + video! Cyber Monday Sale! Download Now
Advertisement
  1. Code
  2. PHP
Code

Manipulating Images in PHP Using GD

by
Difficulty:IntermediateLength:MediumLanguages:

The internet would be pretty dull without images. However, maintaining and manipulating hundreds or thousands of images for your web site can be a headache. As your site design changes, you might need to modify all your images—for example, you might need to convert all your images to grayscale or resize them to 50% of their original size. You might also want to compress or crop different images. Doing this manually is time-consuming and error-prone, but with a little programming knowledge it can be automated.

In this tutorial, you will learn about the GD (Graphic Draw) library in PHP. You'll see how this library can be used to manipulate images by resizing, cropping, rotating or filtering them.

What Is GD?

PHP can do much more than just serve HTML to visitors. For instance, it has the ability to manipulate images. Not only that, but you can also create your own images from scratch and then either save them or serve them to users.

PHP can handle almost all your basic image manipulating needs using the GD library—short for Graphic Draw. 

Setup

If you are working on Windows, you can include the php_gd2.dll file as an extension in php.ini. If you're using something like XAMPP, you will find the php_gd2.dll file in the directory xampp\php\ext. You can also check if GD is installed on your system using the function phpinfo();. If you scroll through the resulting output, you will find something similar to the following.

PHP XAMPP GD

You can also visit the requirements and installation pages to learn more about the installation process.

Creating Images Using PHP GD

The first step towards manipulation of images using PHP is loading them into memory as an image resource. This can be achieved by using different functions for different formats. All these functions have very similar names so they are easy to remember.

Create a New Image

The imagecreatetruecolor() function will prove helpful if you don't have an original image source that you want to manipulate. It accepts two integer parameters: a width and height. It will return an image resource if everything went as planned. The returned image resource is basically a black image with specified width and height.

Load an Image File

If you are planning on manipulating images that are already stored somewhere, you will benefit from using functions like imagecreatefromjpeg(), imagecreatefrompng(), and imagecreatefromgif(). These will create an image resource with all the data from the loaded image file. These functions accept a single parameter which specifies the location of the image you are loading either as a URL or as a file path.

Create an Image From a String

The GD library also allows you to create images from a string using the imagecreatefromstring() function in PHP. Remember that you will have to use base64_decode() on the given string before imagecreatefromstring(). The function can automatically detect if the image type is JPG, PNG, GIF, or another supported format.

Rotate, Scale, Crop, and Flip an Image

Some common operations that you might want to perform on an image resource are rotation, scaling, cropping, and flipping.

Rotation

You can rotate an image that you have already loaded in the script using the imagerotate() function. It will rotate the image at the provided angle using the center of the image as the center of rotation. The angle is provided as a float value, and PHP considers it to be the degree value for rotation. 

Sometimes, the rotated image will have different dimensions in comparison to the original version. This means that you will end up with an uncovered area after the rotation. The third parameter of the imagerotate() function can be used to specify the background color of the empty area after rotation.

Scaling

It is very easy to scale an image using the GD library. You just have to pass the image resource as well as the width and height to the imagescale() function. If you omit the height, GD will scale the image to the specified width while preserving the aspect ratio. 

You can also specify the mode for scaling the image. It can be set to IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC, etc. One important thing that you need to remember is that this function returns a new scaled image source instead of modifying the original one.

Cropping

You can crop any image resource using the imagecrop() function in GD. The first parameter is the original image resource, and the second parameter is an associative array with the keys x, y, width, and height, specifying the position and dimensions of the cropping window.

Crop and Rotate Images Using PHP

The butterfly image above was cropped using the following code:

Basically, we store the length of the smallest side in the $size variable. This variable is then used to define the boundary of our cropping rectangle. Finally, the image is scaled down such that it is only 300 pixels wide and long. This gives us a properly sized square image.

Flipping Images

Images can be flipped horizontally, vertically or in both directions using the imageflip() function. It accepts the image resource you want to flip as the first parameter and the flip mode as the second parameter. The flip mode can be set to IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, or IMG_FLIP_BOTH.

Example of flipping images

The top left image in the above figure is the original. The top right image was created using IMG_FLIP_HORIZONTAL, the bottom left image was created using IMG_FLIP_VERTICAL, and the bottom right image was created using IMG_FLIP_BOTH. (The crow image is from Pixabay.)

Applying Filters to an Image

GD also has a very useful imagefilter() function which can apply filters on different image resources loaded using the functions from previous images. This function can accept various parameters depending on the filter you are applying.

For starters, specify the image resource and the name of the filter that you want to apply. You can set it to one of the 12 predefined filter types mentioned in the docs

  • IMG_FILTER_NEGATE: reverses the colors in the image
  • IMG_FILTER_GRAYSCALE: removes color from the image
  • IMG_FILTER_BRIGHTNESS: makes the image brighter or darker
  • IMG_FILTER_CONTRAST: increases the image contrast 
  • IMG_FILTER_COLORIZE: tints the image to a selected color
  • IMG_FILTER_EDGEDETECT: highlights the edges of the image
  • IMG_FILTER_EMBOSS: similar to edge detection, but gives each edge a raised look
  • IMG_FILTER_GAUSSIAN_BLUR: blurs the image using the Gaussian method
  • IMG_FILTER_SELECTIVE_BLUR: blurs the image using the selective method
  • IMG_FILTER_MEAN_REMOVAL: an effect to create a stylized image
  • IMG_FILTER_SMOOTH: smooths jagged edges in the image
  • IMG_FILTER_PIXELATE: makes the image look pixelated 

Some filters like NEGATE, GRAYSCALE, EDGE_DETECT and EMBOSS don't need any additional data. Other filters, like BRIGHTNESS, CONTRAST and SMOOTH, can accept an additional parameter which specifies the amount of brightness, contrast, or smoothness of the final image. The PIXELATE parameter allows you to specify two additional parameters: the block size as well as the mode of pixelation. Finally, the COLORIZE filter accepts four parameters which determine the values for the red, green, and blue components as well as the alpha channel.

Applying filters to an image

The image in the top left is the original. The top right image was created using the COLORIZE filter, the bottom left was created using the GRAYSCALE filter, and the image in the bottom right was created using the BRIGHTNESS filter. (This butterfly image was found at Pixabay.)

Other Useful Image Manipulation Functions

You should also know about some other common GD functions that come in handy every now and then.

Get Image Dimensions

You can determine the width and height of an image resource using the imagesx() and imagesy() functions.

Another function called getimagesize() can also be used to get the width and height of an image along with its type. This function returns an array with elements specifying the width, height and format of the image. The first two elements of the array describe the width and height, and the third element contains a constant specifying the file format: one of IMAGETYPE_PNG, IMAGETYPE_GIF, etc.

Saving an Image

Once you have made all the desired changes to an image, you'll most likely want to either output it to the browser or save it as a file. In either case, you will have to use one of the GD output functions like imagejpeg(), imagepng(), or imagegif(). You'll pass your image resource to one of these output functions and, if you want to save the image to a file, you'll specify a filename as well. You can also control the quality of the output image using a third optional parameter depending on the image type.

Resizing All Images in a Directory

Let's apply the knowledge we have gained so far to do something practical. In this section, we will resize all the JPEG images in a particular directory to have a width of 640 pixels. The height will be calculated automatically based on the dimensions of the original image.

We will save the resized images in a new folder titled Resized. All the original images in this case have the same dimensions, but the code will work properly with images that have different sizes and aspect ratios.

In the above code, we begin by using the glob() function to find all the images with a .jpg extension in the directory titled Nature. The image files are stored in an array, and we loop over them one by one.

Since all the images that we want to resize are JPEGs, we use the imagecreatefromjpeg() function to load them into the script. The imagescale() function is then used to resize the image to a specific width—640 pixels in our case. We have not specified a fixed height, so the height will be calculated automatically.

Each of the original image files had -1920x1080 appended to the filename to indicate its dimensions. We use str_replace() on the original file name and replace -1920X1080 with the new image size.

Finally, we save the resized images in a folder named Resized with the new filenames. You can also pass a third parameter to the imagejpeg() function to set the quality of the saved image file. If the third parameter is omitted, the images are saved with a default quality of 75.

Apply Grayscale and Contrast Filters on Each Image in a Directory

This time, we will be applying two different filters on each image in our directory and saving the final result in a different directory without making any changes to the file name. Let's dive into the code, and I will explain what each function does later.

As you can see, we load the images from the Nature directory exactly like we did for the previous example. However, we'll use the imagefilter() function this time to apply filters on the loaded image resource. 

Notice that imagefilter() modifies the original image and returns TRUE or FALSE based on the success or failure of the operation. This is different from the imagescale() function we used in the previous section, which returned the scaled image resource.

Another important thing to keep in mind is that the contrast filter accepts values from -100 to 100. Negative values imply more contrast, and positive values imply less contrast. This is the opposite of what some people might expect! A value of 0 will leave the image unchanged.

The brightness filter, on the other hand, has minimum and maximum limits of -255 and 255. The negative value in this case implies minimum brightness, and the positive value implies maximum brightness.

We get the file name from the file path using the basename() function and then save the image using the imagejpeg() function.

Final Thoughts

The aim of this tutorial was to get you familiar with the GD library in PHP and to show you how to use all these functions to make your life easier. You can use the examples at the end of the tutorial as a guide to write your own image manipulation scripts. For example, you can resize an image only if it is wider than a given limit by determining its width using the imagesx() function.

All these functions open up a lot of possibilities to make image manipulation easier and save you a lot of time in the end. If you have any questions related to this tutorial, please let me know in the comments.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.