Flip image with PHP and GD

PHP provides GD library which is very useful for image manipulation. We can easily resize, rotate and flips images using various functions of GD library.

In this tutorial, we will learn how to flip an image horizontally or vertically. This tutorial is for PHP version < 5.5, because in latest PHP5, there is inbuilt function available to flip the image, i.e. imageflip().
Now, we need one source image to flip i.e. image.jpg. Let’s first get the image information using getimagesize() and store the dimensions.

Let’s create an image object from source image and temporary image object to store our flipped image.

We will resample the image to flip it using imagecopyresampled(). This function is used to copy portion of one image to another image.

Now to flip it vertically,

Or to flip it horizontally,

Now, save the $tmpImage to a file.

That’s it. See the full code below.

In latest PHP version (>= 5.5), you can do this same thing using single function. For example,

You may also like...