Posted on September 8th, 2008
7927 views
PHP GD Image Reflections
by dividedbyzero [Example Image] In this tutorial, I shall explain to you how to create an image reflection in PHP using GD. Now there is, of course, a possibility that you don't really care HOW it's done, and just want the end result. If so, here's the final code. Final Code
Now, without further ado, let's begin! Open up your favorite PHP editing software. It's time to start coding!
In the above code, important variables are being set. First of all, the path to your input image. Make sure you set that, or you'll just be bombarded with errors. Please make sure your image is a JPEG. Next is the reflection height. This is pretty self-explanatory; it sets the height of the reflection image. Now we set the starting transparency. This affects how fast the reflection will fade, and how light the reflection will be. By now we only have one variable left to set; "$div". This sets the size of the divider line at the top of your reflection. If you look at the example image, you'll see a white line between the input image and the reflection. This is the divider line (set to 1).
Nothing too important happening here. The input image is stored in a variable, the line we'll be using to apply transparency is created, and a background image is made to accommodate a chunk of the input image. If you would like your reflection to fade to a color besides white, change the value of "$bgc", using imagecolorallocate($li, R, G, B).
Here we go. Finally, some action! The input image is flipped and placed onto the previously created BG image using imagecopyresampled(). Only a chunk of the image specified by the reflection height variable will be placed. Now, the image is still not properly rotated, so it's flipped horizontally using the imagecopy() function. This FOR loop will take 1px vertical lines from the reflection image and place them on the opposite side, effectively flipping the image. Then, to make things make a bit more sense, we take the contents of "$bg" and store them in the more appropriate "$im".
Now we get started on applying the transparency. In this FOR loop, a horizontal line spanning across the reflection image is placed on every Y value, with increasing transparency each time. After this, we apply the divider to the top of the reflection.
The page is defined as a JPEG image using header(), the final image is outputted, and we destroy the image variables to clear some space. Save this into the same directory as your input image and test it out. If you followed the tutorial properly, you should have a nice image reflection. If so, congratulations! If not, please double check the entire code and make sure everything's in tact. Fin. |