Saturday, April 2, 2011

Rotate Image - PHP (GD Library Elaborated)

Hi,

GD library is such a strong architecture, that you can do anything using it. If you want to rotate a simple jpeg file using PHP, this is the code that is needed:


<?php
$im=imagecreatefromjpeg("img.jpg");
$white=imagecolorallocate($im,255,255,255);
$im=imagerotate($im,20,$white);

header("content-type: image/jpeg");
imagejpeg($im);

The image transformation from original to rotated image is as follows respectively:                                      
       


Explanation:

The most important thing you need to remember while using GD library is to initialize your canvas. This can be done in 2 ways. Either you can start with a empty canvas and start adding things to it, such as image, text etc (Click here for an example) or you can start of with a already existing image and modify it. In the above example, I am starting with an existing image as per the requirement.

Since I am not creating anything new, rather editing an existing image, so I am using, "imagecreatefromjpeg("img.jpg");" to create the drawing canvas containing the image, "img.jpg". Now if I am rotating an image, there will be empty space created. To fill that space, I first create a color object of white color by:
$white=imagecolorallocate($im,255,255,255);

Now I am simply rotating the entire image by:
$im=imagerotate($im,20,$white);

$im=image canvas
20=rotation angle
$white=color object for filling the empty space after rotation

Once the rotation is completed, now we are just assigning the page header as jpeg, so that the output is in an image format by:
header("content-type: image/jpeg"); and
imagejpeg($im); is added to generate the image.

:)


No comments:

Post a Comment