Introduction To Image Rotation Using PHP GD Library
imagerotate($source, $degrees, $bgd_color,$ignore_transparent);
$source = An image resource, returned by one of the image creation functions.
$degrees = Value of the angle you want to rotate.
$bgd_color = Specifies the color of the uncovered zone after the rotation .(-1 will make it transparent)
$ignore_transparent = If set and non-zero, transparent colors are ignored.
It’s imporatant to note that imagerotate function will rotate the images with any given angle in anticlockwise method. You can rotate images in clockwise direction using minus values for angle( -90).
Online Image Rotator Demo and Download
Creating Online Image Rotator
// File and rotation $url = 'http://localhost/gd-image-rotate/innovative.jpg'; $degrees = isset($_POST['deg']) ? $_POST['deg'] : '0'; $filename = "demo" . basename($url); // Load $source = imagecreatefromjpeg($url); // Rotate $rotate = imagerotate($source, $degrees, -1); // Output imagejpeg($rotate, $filename, 90); chmod($filename, 0777);
- First I have defined the url of the online source image. In this tutorial i have hard coded the image file.
- You have to create a text box to enter the url and load image if you want it to be put online for dynamic images.
- Then i have set the degrees to rotate using the button values on the html form. Once the button is clicked the value of the angle can be accessed using $_POST['deg'].
- Then get the name of the file using basename function and add demo prefix to the file name.
- If you rotate the same image over and over it’s quality tend to decrease. So always use the original image for rotation and create a copy of rotated image. I have used the demo prefix to create a copy of rotataed image.
- Then create a image resource by passing the image url to the imagecreatefromjpeg function.
- Now you can rotate the image using imagerotate function. Parameter number 3 is given the value of -1 which means uncovered area after rotation will be transparent.
- Then we output the rotated image to the image folder with necessary file permissions.
- Now let’s take a look at the html form. There are 4 submit buttons with the same name deg. When any of this buttons are clicked form will be submitted and image will be rotated by number of degrees defined in the button value.
- Last we pass the name of the image to the src attribute of image tag.
- Now we have created a simple online image rotator using php gd library. Check out the demo and extend the functionality to make this valuable.
Whats Next ?
Use these parameter values correctly according to the function. Specifying a value for imagepng in the range of 0-100 will generate an warning “gd-png: fatal libpng error: zlib failed to initialize compressor” and the output image will not be generated properly