Tuesday, August 31, 2010

2:10 AM

GD library in PHP is very useful for image processing and you can do a lot image manipulation from it. In this post, I’ll show you a simple Image manipulation (image rotation)using the function provided below in PHP. You’ll see how easy it is to rotate an image using PHP.

Function to rotate image using GD library of PHP

function rotateImage($sourceFile,$destImageName,$degreeOfRotation)
{
  //function to rotate an image in PHP
  //developed by Roshan Bhattara (http://roshanbh.com.np)
  //get the detail of the image
  $imageinfo=getimagesize($sourceFile);
  switch($imageinfo['mime'])
  {
   //create the image according to the content type
   case "image/jpg":
   case "image/jpeg":
   case "image/pjpeg": //for IE
        $src_img=imagecreatefromjpeg("$sourceFile");
                break;
    case "image/gif":
        $src_img = imagecreatefromgif("$sourceFile");
                break;
    case "image/png":
        case "image/x-png": //for IE
        $src_img = imagecreatefrompng("$sourceFile");
                break;
  }
  //rotate the image according to the spcified degree
  $src_img = imagerotate($src_img, $degreeOfRotation, 0);
  //output the image to a file
  imagejpeg ($src_img,$destImageName);
}

The above function takes takes three argument, first one is the source image to be rotated and the second one is the name of file which is resulted after rotating the original image. And, the last parameter is the degree of the rotation of Image.
In this PHP function, first of all the information about the source image is stored in “$imageinfo” array. The MIME type of the file are stored in “mime” key of the “$imageinfo” array. And then appropriate image resource is created using the proper MIME type. And then, imagerotate() function of PHP is used for the rotation of the image then imagejpeg() is used to output the image to a file.

Now let’s look at the php code to call the above function see the result of rotated image with that function

 <?php rotateImage('image.jpg','rotated.jpg',90); ?> 


0 comments: