function to rotate an image.

image rotate” makes use of the built-in PHP functions getimagesize( ), imagecreatefromjpeg( ), imagecreatetruecolor( ), imagecopyresampled( ), imagerotate( ) and imagejpeg( ).

01 <?php
02 
03 function rotatepix($sourcefile, $targetfile, $degrees)
04 {
05     $img_size = getimagesize($sourcefile);
06     $x = $img_size[0];
07     $y = $img_size[1];
08     if ($x > $y)
09     {
10         $dst_x = 0;
11         $dst_y = $x - $y;
12         $newd = $x;
13     }else{
14         $dst_x = $y - $x;
15         $dst_y = 0;
16         $newd = $y;
17     }
18     $src_img = imagecreatefromjpeg($sourcefile);
19     $dst_img = imagecreatetruecolor($newd,$newd);
20  
21     if ((($x > y) && ($degrees < 180)) || (($y > $x) && ($degrees > 180)))
22         imagecopyresampled($dst_img,$src_img,0,0,0,0,$x,$y,$x,$y);
23     else
24         imagecopyresampled($dst_img,$src_img,$dst_x,$dst_y,0,0,$x,$y,$x,$y);
25  
26     $rotated_img = imagerotate($dst_img, $degrees,0);
27  
28     if($degrees != 180)
29     {
30         // 90 counterclockwise or clockwise
31         $final_img = imagecreatetruecolor($y,$x);
32         imagecopyresampled($final_img,$rotated_img,0,0,0,0,$y,$x,$y,$x);
33     }else{
34         // 180 degrees
35         $final_img = imagecreatetruecolor($x,$y);
36         imagecopyresampled($final_img,$rotated_img,0,0,0,0,$x,$y,$x,$y);
37     }
38     imagejpeg($final_img, $targetfile);
39 }
40  
41 ?>